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

1

6

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?

Denunciate answered 14/8, 2014 at 20:24 Comment(1)
Looks like this route is getting overrided by the default route in the RouteConfig File. Try out coment that route to see what happens.Holding
S
4

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 }, ...)
Substratosphere answered 14/8, 2014 at 21:27 Comment(1)
Changing the order worked... Genius that it was something so simple.Denunciate

© 2022 - 2024 — McMap. All rights reserved.