Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeRouting ActionLink helper rendering query string value instead of including parameter in route

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?

like image 637
Modika Avatar asked Aug 14 '14 20:08

Modika


1 Answers

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 }, ...)
like image 115
Chris Pratt Avatar answered Oct 20 '22 15:10

Chris Pratt