I am working on my first MVC project and using attribute routing within my controllers. I am having a slight issue with one of my actions which has two possible route paths. The routes themselves are working but the actionLinks being generated 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 when a currentCategoryId is not null the link produced is this:
/categories/add?parentId=2
but what i would like to see (which is picked up when you hand roll the url) is:
/categories/2/add
is there anyway i can achieve this with the actionLink or any other MVC magic?
Try:
[Route("add", Order = 2)]
[Route("{parentId:int?}/add", Order = 1)]
That still may not work because the fact that you have a route that doesn't require a parameter may short-circuit the routing logic regardless. Another option would be to name each route and then explicitly state the one your want:
[Route("add", Name = "AddCategory")]
[Route("{parentId:int?}/add", Name = "AddCategoryForParentId")]
Then:
@Html.RouteLink("Add Category", "AddCategoryForParentId", new { parentId = @Model.CurrentCategoryId }, ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With