ASP MVC路由与> 1参数 [英] ASP MVC Routing with > 1 parameter

查看:67
本文介绍了ASP MVC路由与> 1参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下途径定义

            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.

不过,如果我尝试构建在视图中的链接以url.action -

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})%>

我得到以下网址

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

它仍然有效,但不是很干净。任何想法?

It still works, but isn't very clean. Any ideas?

推荐答案

在构造和ASP.NET路由匹配的路由(这是ASP.NET MVC使用),第一个合适的匹配使用,而不是贪婪,和顺序很重要。

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.

在事实上,因为你为{项目名称}和{name}的提供的默认值,这是完全符合的默认路由发生冲突。这里是你的选择:

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.

使用RouteLinks代替ActionLinks,具体命名你想要的路线,以便使其正确的链接毫不含糊。

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

这篇关于ASP MVC路由与&GT; 1参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆