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

Tag Helper Syntax for View Components

DZone 's Guide to

Tag Helper Syntax for View Components

Calling view components in ASP.NET Core views may lead to long and ugly code lines containing generic type parameter of view component and anonymous type for...

· Web Dev Zone ·
Free Resource

Calling view components in ASP.NET Core views may lead to long and ugly code lines containing generic type parameter of view component and anonymous type for InvokeAsync()method parameters. Something my readers have been interested in for a long time is the tag helper syntax for view components.

ASP.NET Core Pager Example

Suppose you have pager implemented as view component and there's support for multiple views.

public class PagerViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(PagedResultBase pagedResult, 
                                                        string viewName = "Default")
    {
        var action = RouteData.Values["action"].ToString();
        pagedResult.LinkTemplate = Url.Action(action, new { page = "{0}" });
 
        return await Task.FromResult(View(viewName, pagedResult));
    }
}

This is how you call pager view component in views. Arguments are given as anonymous objects that are matched by an argument list of the component's InvokeAsync() |method.

@(await Component.InvokeAsync<PagerViewComponent>(new { pagedResult = Model, viewName = "PagerSmall" }))

The nice thing is that you don't need such a long call in your views. ASP.NET Core supports a special tag helper syntax for view components. There's a special namespace called "vc" and through this we can call view components using the tag helper syntax. You can replace the call above with shorter one shown here.

<vc:pager paged-result="@Model" view-name="PagerSmall" />

NB! Make sure you add your view components name space to the _ViewImports.cs file that is located in the Views folder. If you don't, then ASP.NET Core cannot find your view components.

Wrapping Up

View components and tag helpers are powerful features in ASP.NET Core. Tag helpers have nice and clean syntax that view components lack when included in views. There's special "vc" tag prefix in ASP.NET Core that brings tag helper syntax for view components to Razor views. Instead of anonymous object with arguments we can use tag attributes to give values to InvokeAsync() method of view component. This leads us to shorter and cleaner views that are easier to handle.

Related Articles by Gunnar Peipman: 

Topics:
web dev ,asp.net core tutorial ,c# tutorial ,tag helper syntax ,tag helpers

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}