Using the .net core anchor tag helper with Razor Pages and areas

With Razor Pages, the anchor tag helper is used somewhat differently than with MVC. A typical anchor tag helper for MVC is:

<a asp-controller="Home" asp-action="Products">Our Products</a>

In this case, you specify the controller as the Home controller and the handler method in the controller as “Products”.

Razor Page Model

In the case of a Razor Page, a typical anchor tag helper is:

<a asp-page="/Products">Our Products</a>

Here, “asp-page” is the name of the razor page and points to example.com/Products. Note that in the MVC model, the “asp-action” did not start with a slash whereas in the Razor Page model the “asp-page” must start with a slash.

If you want to link to example.com/Products/ProductA, it is tempting to just change “asp-page” so that asp-page=/Products/ProductA as if ProductA were an actual page and not a value of the Product field in your model. However, this will not resolve because the “asp-page” parameter has to be the actual name of a page path with nothing added. In this case you must create the “asp-router-{value}” tag.

<a asp-page="/Products" asp-route-product="ProductA">Our Products  </a>

You might want to set the asp-route-Product parameter to @Model.Product to create a dynamic link.

Using areas

Consider a more complex site divided into “areas” . Your folder tree shows two main folders, Electronics, and Household. In this case you can add the asp-area parameter.

<a asp-area="Electronics" asp-page="/Products" asp-route-product="ProductA">Our Products</a>

Folders nested with areas

Suppose you have folders nested within Electronics: CellPhones and Tablets.

Areas
—-Electronics
——–Pages
———— CellPhones
———————Products
———————Support
———– Tablets
———————Products
———————Support
—-Household
——–Pages
————Dishwashers
————Dryers
————-…

<a asp-area="Electronics" asp-page="/CellPhones/Products" asp-route-product="ProductA">Our Products</a>

If you are switching from the MVC model to the Razor Page model, there are lots of little syntax rules that can trip you up. If you are just learning either model it is easy to not notice that the syntax is indeed different.

Leave a Reply

Your email address will not be published. Required fields are marked *