Modika
Modika

Reputation: 6282

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?

Upvotes: 6

Views: 1823

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239380

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 }, ...)

Upvotes: 4

Related Questions