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

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

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

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

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