AttributeRouting ActionLink an auxiliary value of the render query string instead of including the parameter in the route

I am working on my first MVC project and using attribute routing in my controllers. I have a little problem with one of my actions that has two possible route paths. The routes themselves work, but the generated actionLinks are not to my liking.

Routes

[Route("add")] [Route("{parentId:int?}/add")] 

ActionLink Definition:

  @Html.ActionLink("Add Category", "Add", "Category", new { parentId = @Model.CurrentCategoryId}, new { @Class = "btn btn-primary"}) 

This works, but if currentCategoryId is not null, the link:

 /categories/add?parentId=2 

but what I would like to see (which rises when you manually roll the URL):

 /categories/2/add 

Anyway, can I achieve this with actionLink or any other MVC magic?

+5
source share
1 answer

Try:

 [Route("add", Order = 2)] [Route("{parentId:int?}/add", Order = 1)] 

This may still not work, because the fact that you have a route that does not require a parameter can lead to a short circuit of the routing logic. Another option is to name each route, and then explicitly specify the one you want:

 [Route("add", Name = "AddCategory")] [Route("{parentId:int?}/add", Name = "AddCategoryForParentId")] 

Then:

 @Html.RouteLink("Add Category", "AddCategoryForParentId", new { parentId = @Model.CurrentCategoryId }, ...) 
+4
source

Source: https://habr.com/ru/post/1200359/


All Articles