Reputation: 330
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);
}
}
Upvotes: 17
Views: 7138
Reputation: 436
You can do the following :
public IViewComponentResult Invoke()
{
if (User.IsInRole(UserRoles.CLIENT))
return View("_ClientMenu");
return Content(string.Empty);
}
Upvotes: 41
Reputation: 68
A property can inherit from an interface not cast to it.
Try create an object which is inherits from IViewComponentResult.
public class xyz: IViewComponentResult
{
// todo
}
then return this object. It should work.
Upvotes: 0