Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

ASP.NET Core view component tag helper

Suggested Videos
Part 23 - Partial views in asp.net core | Text | Slides
Part 24 - ASP.NET Core view components | Text | Slides
Part 25 - Pass parameters to view component in asp.net core | Text | Slides

In this video we will discuss, how to invoke a view component using View Component as tag helper.

Component.InvokeAsync


One way to invoke a view component is by using Component.InvokeAsync. We use an anonymous type to pass parameters to the view component. The property names in the anonymous type must match the parameter names on the view component invoke method. We discussed this technique of invoking a view component in our previous video.


@await Component.InvokeAsync("View Component Name", {Anonymous Type Containing Parameters})

View component tag helper

To be able to use a view component as a Tag Helper, we have to first register the assembly that contains the view component. We do this in the _ViewImports.cshtml file. 

We discussed ViewImports file in detail in Part 31 of ASP.NET Core tutorial.

It is used to include the common namespaces so we do not have to include them in every view or razor page that needs those namespaces. We also use this file to register built-in tag helpers. To register tag helpers we use @addTagHelper directive. We use this same directive to register view components so they can be used as tag helpers.

@addTagHelper *, RazorPagesTutorial

RazorPagesTutorial, is the assembly (DLL) that contains the view components to register
* (asterisk), specifies all the view components.

Use the tag helper vc (short for view component), and then a colon (:) and then the view component name. Our view component name is HeadCount view component, so we specify head-count.

<vc:head-count department="Dept.IT"></vc:head-count>

In our example, the parameter name contains just one word. It is very common to have parameters with 2 or more words. For example, if the parameter is departmentName, you specify it like the following . This is called kebab case.

<vc:head-count department-name="Dept.IT"></vc:head-count>

asp.net core tutorial for beginners

No comments:

Post a Comment

It would be great if you can help share these free resources