How to return an empty viewcomponent MVC 6?

Viewed 4858

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);
    }
}
2 Answers
Related