Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Returning Empty Content From ASP.NET Core ViewComponent [Snippet]

DZone's Guide to

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.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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:

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));
        }
    }

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

Topics:
c# ,asp.net core ,web dev ,view ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}