ASP MVC Routing with Parameter> 1

I determined the following route

routes.MapRoute( "ItemName", "{controller}/{action}/{projectName}/{name}", new { controller = "Home", action = "Index", name = "", projectName = "" } ); 

This route really works, so if I find in the browser

 /Milestone/Edit/Co-Driver/Feature complete 

It correctly proceeds to the Milestone controller, the editing action, and passes the values.

However, if I try to build a link in a view with url.action -

 <%=Url.Action("Edit", "Milestone", new {name=m.name, projectName=m.Project.title})%> 

I get the following URL

 Milestone/Edit?name=Feature complete&projectName=Co-Driver 

It still works, but not very clean. Any ideas?

+3
source share
3 answers

When constructing and mapping routes in ASP.NET routing (which is what ASP.NET MVC uses), the first matching match is used, and not the most greedy and ordering.

So, if you have two routes:

 "{controller}/{action}/{id}" "{controller}/{action}/{projectName}/{name}" 

in this order, the first one will be used. Additional values, in this case project_name and name, become query parameters.

In fact, since you provided default values ​​for {projectName} and {name}, they completely contradict the default route. Here are your options:

  • Delete the default route. Do this if you no longer need the default route.

  • Carry a longer route and make it more explicit so that it does not match the default route, for example:

     routes.MapRoute( "ItemName", "Home/{action}/{projectName}/{name}", new { controller = "Home", action = "Index", name = "", projectName = "" } ); 

    Thus, any routes with a controller == Home will correspond to the first route, and any routes with a controller! = Home will correspond to the second route.

  • Use RouteLinks instead of ActionLinks, in particular, indicating which route you want it to make the correct link without ambiguity.

+5
source

Just to clarify, here is what I finally did to solve it, thanks to the answer from @Brad

 <%=Html.RouteLink("Edit", "ItemName", new { projectName=m.Project.title, name=m.name, controller="Milestone", action="Edit"})%> 
+1
source

You can try

 Html.RouteLink("Edit","ItemName", new {name=m.name, projectName=m.Project.title}); 
0
source

All Articles