MVC 3.0 Maproute Coding
I am writing a new MVC App; I want to make some changes to the routing to add department name to the URL.
The following is what is generated by VS 2012.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.MapRoute( _
name:="Default", _
url:="{controller}/{action}/{id}", _
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
)
I want to pass the department name in the beginning of the path. ex.
http: // localhost: /hr/Home/Contact
http: //localhost /hr/Home/About
http: //localhost /finance/Home/Contact
http: //localhost /finance/Home/About
http: //localhost /marketing/Home/Contact
http: //localhost /marketing/Home/About
Instead of the default pages:
http: //localhost /Home/About http: //localhost /Home/Contact
That should be pretty straight forward; add department
to the start of the route:
routes.MapRoute( _
name:="DepartmentRoute", _
url:="{department}/{controller}/{action}/{id}", _
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
)
You might want to also add a constraint to make sure it only matches department names:
constraints:=New With { .department = @"[hr|finance|marketing]" }
There are two ways to access the department name once you have it in the URL. One way is to use the property RouteData.Values like this:
string department = RouteData.Values["department"];
The other way is more elegant. If we define parameters to our action method with names that match the URL pattern variables, the MVC Framework will pass the values obtained from the URL as parameters to the action method.
public ViewResult Index(string department) {
ViewBag.Department = department;
return View();
}
链接地址: http://www.djcxy.com/p/57856.html
上一篇: 在asp.net mvc 4中自定义路由
下一篇: MVC 3.0 Maproute编码