Search code examples
asp.net-corerazor

Anchor Tag Helper with Route Data


I have the following file structure:

  • Areas directory
    • Users directory
      • Index.cshtml
      • Index.cshtml.cs
      • Edit directory
        • UserEdit.cshtml
        • UserEdit.cshtml.cs

The route for the users index page is /users. The route for a given user's edit page is /users/{userId}/edit. The routes are setup with routing within the razor page like @page "/users"

I'm trying to use anchor tag helpers to link between the index page and the edit page(s). However, the standards marked in Microsoft's documentation don't seem to work unless I'm missing something. Is there a way to use anchor tag helpers to route between pages that have route data?

Note that I am using razor pages with models. I am not using controllers, and my routing is not using named routes.

With the example given below, the "edit" link's URL just keeps me at the index page.

Index.cshtml

@page "/users"
@model MyApp.Areas.Users.Pages.IndexModel

<table>
    <thead>
        <tr>
            <th>Username</th>
            <th>Edit</th>
        </tr>
    </thead>
    <tbody>
        @foreach(User user in this.Model.Users)
        {
            <tr>
                <td>@user.Username</td>
                <td><a asp-page="/Edit" asp-route-userId="@user.UserId">Edit</a></td>
            </tr>
        }
    </tbody>
</table>

Edit.cshtml

@page "/users/{userId}/edit"
@model MyApp.Areas.Users.Pages.Edit.UserEditModel

<div>The user edit page for @this.Model.User.Username</div>

Edit - 8/31/2021

Adding more information around how routing is configured in my application.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddRazorPages()
        .AddCookieTempDataProvider(opt =>
        {
            opt.Cookie.IsEssential = true;
        })
        .AddRazorRuntimeCompilation();

    services.AddControllers(opt =>
    {
        AuthorizationPolicy _policy = new()
            .RequireAuthenticatedUser()
            .Build();
        opt.Filters.Add(new AuthorizeFilter(_policy);
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...

    app.UseHttpRedirection();
    app.UseStaticFiles();

    app.UseCookiePolicy();

    app.UseRouting();

    ...

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

I have a _ViewImports.cshtml in both my base Pages directory and within my Areas\Users directory.

~\Pages\_ViewImports.cshtml

@namespace MyApp.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

~\Areas\Users\_ViewImports.cshtml

@namespace MyApp.Areas.Users
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Solution

  • As discussed in Link not rendering when using asp-page TagHelper, you have to specify the name of the cshtml file in the asp-page tag property, like:

    <a asp-page="Users/Edit/UserEdit" asp-route-userId="@user.UserId">Edit</a>