简体   繁体   中英

ASP.NET Core Endpoint Routing Link Generation in Views

I'm having an issue while trying to upgrade my ASP.NET Core 2.1 application to 2.2 and use endpoint routing. The link generation works differently and I'm pretty sure it relates entirely to that.

I use link generation within the views to generate links. In some cases I currently do something like this:

let url = "@Url.Action(nameof(NoteController.Category), PortalControllerNames.Note)/" + categoryItem.dataset.categoryId + "/@Model.UserId";

The route for this action is defined as below, which I understand essentially says categoryId and userId are required:

[HttpGet("[controller]/[action]/{categoryId}/{userId}")]

In 2.1 the following is generated from the call to @Url.Action

let url = "/Note/Category/" + categoryItem.dataset.categoryId + "/12345";

Which I can then slot the additional parameter into at runtime via javascript.

Under 2.2 with Endpoint Routing enabled the route isn't found and an empty string is returned as per the official docs .

Benefits of using the Url.Action method are things like passing action method names and having the system resolve the route name for them meaning that any change to controller names is carried out via refactoring in VS and any route name changes are automatically carried through the application with no view changes needed.

I understand that the route doesn't exist to be looked up and think this is cause of the issue. Is a solution to just add a route that will allow generation of the "base" route (without the parameters)? (I think this would have the side effect that you can now navigate to the route without the parameters being present whereas you'd currently get a 404 when doing so because no route is satisfied?)

Does anyone know of or have an idea how I can retain the "strongly typed" nature of link generation with the new system or is it not possible anymore?


Side Note

An alternate solution might also be to generate a unique link for each category item (that way you could use link generation) but that means you have to generate a link for each category and send it in the response which would increase data sent to the browser (not by much I admit but every little helps)

Have you considered using taghelpers ?

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/anchor-tag-helper?view=aspnetcore-2.2

Take a look at the asp-route-{value} section.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/anchor-tag-helper?view=aspnetcore-2.2#asp-route-value

you could put a 'stub' value as route-value and replace it using your java-script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM