ASP MVC Routing with > 1 parameter

99封情书 提交于 2019-12-03 10:17:44

问题


I have the following route defined

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

This route actually works, so if I type in the browser

/Milestone/Edit/Co-Driver/Feature complete

It correctly goes to the Milestone controller, the edit action and passes the values.

However, if I try and construct the link in the view with a 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 isn't very clean. Any ideas?


回答1:


When constructing and matching routes in ASP.NET routing (which is what ASP.NET MVC uses), the first appropriate match is used, not the greediest, and order is important.

So if you have two routes:

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

in that given order, then the first one will be used. The extra values, in this case projectName and name, become query parameters.

In fact, since you've provided default values for {projectName} and {name}, it's fully in conflict with the default route. Here are your choices:

  • Remove the default route. Do this if you don't need the default route any more.

  • Move the longer route first, and make it more explicit so that it doesn't match the default route, such as:

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

    This way, any routes with controller == Home will match the first route, and any routes with controller != Home will match the second route.

  • Use RouteLinks instead of ActionLinks, specifically naming which route you want so that it makes the correct link without ambiguity.




回答2:


Just to clear up, 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"})%>



回答3:


You can try

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


来源:https://stackoverflow.com/questions/323572/asp-mvc-routing-with-1-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!