jamheadart
jamheadart

Reputation: 5343

Can we use addTagHelper in razor pages?

In an ASP.NET CORE 3.1 MVC project, I added a Custom TagHelper in

Views > _ViewImports.cshtml

The markup is now working fine in all the views within that folder.

I also scaffolded the AspNetCore.Identity pages so in my project I also have

Areas > Identity > Pages > _ViewImports.cshtml

and then a whole bunch of Razor pages in

Areas > Identity > Pages > Account > ...

Now whether I add the TagHelper to the _ViewImports.cshtml or even directly on to any of those Razor pages, the markup just doesn't work.

Do Razor pages in Areas not work the same with TagHelpers? Can I add TagHelpers to .cshtml pages in this way or does it only work on .cshtml pages in the Views folder?

Upvotes: 1

Views: 1902

Answers (2)

Zhi Lv
Zhi Lv

Reputation: 21656

If add the addTagHelper directive in the Areas > Identity > Pages > _ViewImports.cshtml page, only the identity razor pages could use the custom tag helper. The view pages in the Views folder can't use the custom tag helper.

To make the Views folder's pages to use the custom tag helper, we should add the addTagHelper directive in the Views > _ViewImports.cshtml page.

To make the Views folder's page and the Identity razor pages to use the custom tag helper, we need to add the addTagHelper directive both in the Areas > Identity > Pages > _ViewImports.cshtml and Views > _ViewImports.cshtml.

Besides, as AntonKovachev said, when we add the addTagHelper directive, we should use the project name. For example, my project name is "netcore3", and I created a MyCustomTagHelper in the Taghelpers folder, then, the addTagHelper directive should like this (you can change the project name or the file path to yours):

@addTagHelper *, netcore3

or

@addTagHelper netcore3.TagHelpers.MyCustomTagHelper, netcore3

check the following screenshot (the login and register page is the Identity razor page, and the Index page is the View page.):

enter image description here

Upvotes: 2

Anton Kovachev
Anton Kovachev

Reputation: 347

TagHelper should be absolutely ok with Razor Pages. Just add @addTagHelper *, <ProjectName> to your _ViewImports.cshtml where <ProjectName> is the name of the project where your custom TagHelper is defined. The wildcard * will make all tag helpers that are defined in available to all views that inherit from _ViewImports.cshtml. If you wish to make only one specific TagHelper available to all views that inherit from _ViewImports.cshtml add @addTagHelper <SpecificTagHeler>, <ProjectName> where SpecificTagHelper is the fully qualified name of your tag helper for example AuthoringTagHelpers.TagHelpers.EmailTagHelper and <ProjectName> is the name of your project or assemby where the TagHelper is defined for example AuthoringTagHelpers i.e.

@addTagHelper AuthoringTagHelpers.TagHelpers.EmailTagHelper, AuthoringTagHelpers

or

@addTagHelper *, AuthoringTagHelpers

Upvotes: 1

Related Questions