I have the following file structure:
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.
@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>
@page "/users/{userId}/edit"
@model MyApp.Areas.Users.Pages.Edit.UserEditModel
<div>The user edit page for @this.Model.User.Username</div>
Adding more information around how routing is configured in my application.
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.
@namespace MyApp.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@namespace MyApp.Areas.Users
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
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>