I have searched but I did not find any way to return an empty IViewComponentResult. The only way I managed to do it is by returning an empty View. Is there a better way? This is my code:
public class ClientNavigationViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
return User.IsInRole(UserRoles.CLIENT)
? View("_ClientMenu")
: (IViewComponentResult)new EmptyResult();
}
}
This is the exception:
An exception of type 'System.InvalidCastException' occurred in but was not handled in user code
Additional information: Unable to cast object of type 'Microsoft.AspNet.Mvc.EmptyResult' to type 'Microsoft.AspNet.Mvc.IViewComponentResult'.
I have tried to return null but that won't work too. Any ideas? EDIT Made it work like this:
public class ClientNavigationViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
if (User.IsInRole(UserRoles.CLIENT))
return View("_ClientMenu");
return new EmptyViewComponent();
}
}
public class EmptyViewComponent : IViewComponentResult
{
public void Execute(ViewComponentContext context)
{
}
public Task ExecuteAsync(ViewComponentContext context)
{
return Task.FromResult(0);
}
}
Walkthrough: Creating a simple view component Add a ViewComponent class. View component classes can be contained in any folder in the project. Because the class name... Create the view component Razor view. Create the Views/Shared/Components folder. This folder must be named Components. Specifying a ...
View components are typically invoked from a view, but you can invoke them directly from a controller method. While view components don't define endpoints like controllers, you can easily implement a controller action that returns the content of a ViewComponentResult. In this example, the view component is called directly from the controller:
A view component defines its logic in an InvokeAsync method that returns a Task<IViewComponentResult> or in a synchronous Invoke method that returns an IViewComponentResult. Parameters come directly from invocation of the view component, not from model binding. A view component never directly handles a request.
public IViewComponentResult Invoke () { if (User.IsInRole (UserRoles.CLIENT)) return View ("_ClientMenu"); return Content (string.Empty); } A property can inherit from an interface not cast to it. Try create an object which is inherits from IViewComponentResult. then return this object. It should work.
You can do the following :
public IViewComponentResult Invoke()
{
if (User.IsInRole(UserRoles.CLIENT))
return View("_ClientMenu");
return Content(string.Empty);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With