Returning Empty Content From ASP.NET Core ViewComponent [Snippet]
This post is a quick one but a good one. In it, an experienced developer teaches us how to handle the tricky issue of returning empty content.
Join the DZone community and get the full member experience.
Join For FreeASP.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:

In most 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 situations 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));
}
}
Published at DZone with permission of Mikael Koskinen, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments