0 Comments

ASP.NET Core ViewComponents usually come in pairs: There’s the class which inherits ViewComponent and there’s the Razor view which is returned by the class:

image

In most of the situations the ViewComponent runs some logic and then returns the view:

    public class MyTest : ViewComponent
    {
        public Task<IViewComponentResult> InvokeAsync(string content)
        {
            return Task.FromResult<IViewComponentResult>(View("Default"));
        }
    }

But what if you need to return the view only in some cases based on the ViewComponent’s parameters or because of some other validation? In these situation you can skip returning the view by returning empty content instead:

    public class MyTest : ViewComponent
    {
        public Task<IViewComponentResult> InvokeAsync(string content)
        {

            if (string.IsNullOrWhiteSpace(content))
            {
                return Task.FromResult<IViewComponentResult>(Content(string.Empty));
            }

            return Task.FromResult<IViewComponentResult>(View("Default", content));
        }
    }