日期:2014-05-16  浏览次数:20833 次

Asp.Net MVC4 系列--进阶篇之路由 (2)

上一篇介绍了Asp.Net MVC 中,从Http Pipeline上接收到请求如何匹配,匹配限制,以及如何控制在指定命名空间查找,解析出controller和action,并传参。

这篇主要介绍如何使用路由完成url生成,实现页面跳转,以及customize一个路由。

在view中生成一个url连接

 

路由配置使用默认生成的:

routes.MapRoute(
                name:"Default",
                url:"{controller}/{action}/{id}",
                defaults: new { controller ="Home", action = "Index", id = UrlParameter.Optional }
            );


 

最简单的方法是使用Html.ActionLink ,在home View里添加代码:

@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport"content="width=device-width" />
<title>ActionName</title>
</head>
<body>
<div>The controller is:@ViewBag.Controller</div>
<div>The action is: @ViewBag.Action</div>
<div>
@Html.ActionLink("This is an outgoing URL", "CustomVariable") 
</div>
</body>
</html>


 

这样就会生成:

<a href="/Home/CustomVariable">This is anoutgoing URL</a>


这样,实际上是生成了在当前controller内,指向另一个action的url。

使用Html.ActionLink生成链接的好处是什么,可以根据当前的路由配置,自动维护生成好的url,上例使用的是默认配置。例如如果路由配置改为:

routes.MapRoute("NewRoute","App/Do{action}",
new { controller = "Home" });

使用同样的代码:

@Html.ActionLink("This is an outgoing URL","CustomVariable")


此时url连接就会生成为:

<a href="/App/DoCustomVariable">This is anoutgoing URL</a>


因为当我们访问home controller时,NewRoute 在默认路由之前被匹配到了,就会拿它的pattern来生成url了。

当一个请求来时,路由会检测:

1.      Pattern

2.      路由限制

3.      Assign给匿名对象的默认值,就是解析存在Route Dictionary 里面的那些值

 

跳转到其他controller

最简单的方式:

@Html.ActionLink("Thistargets another controller", "Index", "Admin")


直接传入第二个参数,指向”admin”controller


生成url连接,同时传参

对于同一个controller:

@Html.ActionLink("This is anoutgoing URL",
"CustomVariable", new {id = "Hello" })


跨controller传值:

 @Html.ActionLink("Click me to go to anotherarea","Index", "Test",new {Id="aaa"},null)


 

注意,如果路由成功匹配了传值的参数名称,那么url就会以匹配的格式生成;如果路由匹配成功,可是传的值没有在路由模式中指定,那么就会以?param=value的形式传值。例如,对于以上actionlink,如果是路由:

routes.MapRoute("NewRoute","App/Do{action}",
new { controller ="Home" })


那么生成的url连接就是: