Samuel Johnson
Samuel Johnson

Reputation: 363

ASP.NET Core 5 AnchorTagHelper not working on razor page

I have a simple anchor tag helper in my Razor _layout.cshtml page; however no url is appearing on the first one but is on the second.

The asp-for attribute is pulling the value from a simple const string and both tag helpers are obtaining it from the same place.

public static class PageNavigation
{
    public const string Manage = "/account/manage";
    public const string Logout = "/account/logout";
}

Tag helper in _layout.cshtml page:

<a asp-page="@PageNavigation.Manage" class="dropdown-item notify-item">
    <i class="mdi mdi-account-circle mr-1"></i>
    <span>My Account</span>
</a>

<a asp-page="@PageNavigation.Logout" class="dropdown-item notify-item">
    <i class="mdi mdi-account-circle mr-1"></i>
    <span>Logout</span>
</a>

Output:

<a class="dropdown-item notify-item" href="">
    <i class="mdi mdi-account-circle mr-1"></i>
    <span>My Account</span>
</a>
<a class="dropdown-item notify-item" href="/account/logout/">
    <i class="mdi mdi-logout mr-1"></i>
    <span>Logout</span>
</a>

As you can see, the first tag has no href attribute value; this is a bit weird and I cannot work out why and unfortunately I cannot easily debug into the AnchorTagHelper native source, I only end up in the output writer classes and not the actual tag helper source.

EDIT:

Further editing indicates I cannot seem to output anything but a single anchor tag helper in this manner ... no matter how many create, in any order, only the "Logout" one appears correctly.

The only way for me to get this to work is to just use a normal anchor tag using the href attribute.

On a separate point; it makes me wonder what the point of the Anchor Tag helper is for Razor pages. You can't map it in a strongly typed manner to a specific Razor page and even with 'route' attributes, its a very long-winded way of just adding an anchor tag like normal.

Upvotes: 0

Views: 1396

Answers (1)

Mike Brind
Mike Brind

Reputation: 30120

See Note 3 here: https://www.learnrazorpages.com/razor-pages/tag-helpers/anchor-tag-helper

The asp-page attribute needs the path to the file without the extension, not the path to the folder.

public static class PageNavigation
{
    public const string Manage = "/account/manage/index";
    public const string Logout = "/account/logout";
}

Edit - on your separate point, the anchor tag helper, given the correct page name, will generate the right URL for that page, which may not necessarily match its file path.

Upvotes: 1

Related Questions