前后台獲取Action、Controller、ID名方法
- 前台頁面:ViewContext.RouteData.Values["Action"].ToString();//獲取Action名稱
ViewContext.RouteData.Values["Controller"].ToString();//獲取控制器名稱
ViewContext.RouteData.Values["ID"].ToString();//獲取路由參數值:
- 后台頁面:ControllerContext.RouteData.GetRequiredString("Action");
ControllerContext.RouteData.GetRequiredString("Controller");
ControllerContext.RouteData.GetRequiredString("id");
路由規則示例
路由規則是有優先級的,上面的優先級高。
routes.MapRoute( name: "test", url: "test1/{action}/{id}", defaults: new { controller = "Test", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "datacenter", url: "data/{action}", defaults: new { controller = "DataCenter", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
當訪問../test1頁面時會匹配到第一個路由規則,對應的控制器和行為:Test/Index。訪問../test1/add時,對應Test/Add
當訪問../data頁面時會匹配到第二個路由規則,對應的控制器和行為:DataCenter/Index。訪問../data/add時,對應DataCenter/Add
當訪問../Test或../DataCenter或../時都會匹配到第三個路由規則,第三個路由規則為系統自動生成的