RoutData.values[Key] 只能獲取路由定義中的數據,url參數的數據不包含在裡面 https://i.cnblogs.com/EditPosts.aspx?opt=1 路由:功能變數名稱到?之間 -->EditPosts.aspx URL參數:?之後 -->opt=1 修改路由規則後 ...
RoutData.values[Key] 只能獲取路由定義中的數據,url參數的數據不包含在裡面
https://i.cnblogs.com/EditPosts.aspx?opt=1
路由:功能變數名稱到?之間 -->EditPosts.aspx
URL參數:?之後 -->opt=1
//View頁面添加鏈接 <a href='@Url.Action("StudentDetail","Student",new {id=1001,age=20,gender=1})'>查看學員詳情</a> //路由表 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = 10 } );
//映射得到的地址如下
<a href="/Student/StudentDetail/1001?age=20&gender=1">查看學員詳情</a>
//控制器中方法 public ActionResult StudentDetail(int age,int gender) { //使用的是RouteData中的數據 ViewBag.id =RouteData.Values["id"]; //使用的是方法的參數映射 ViewBag.age=age; ViewBag.gender = gender; return View(); } //StudentDetail視圖中的展示 <div> @*在視圖中輸出控制器中獲取的數據*@ @ViewBag.id<br /> @ViewBag.gender<br /> @*在視圖中直接輸出*@ @ViewContext.RouteData.Values["controller"] <br /> @*在視圖中遍歷*@ @{ foreach (KeyValuePair<string, object> data in @ViewContext.RouteData.Values) { var info = data.Key + ":" + data.Value; @info @*顯示到頁面*@<br /> } } </div>
1001 //
1
Student
//因為路由中只有以下三個參數,所以,不會遍歷獲取到age及gender
controller:Student
action:StudentDetail
id:1001
修改路由規則後
//鏈接配置 <a href='@Url.Action("StudentDetail","Student",new {id=1001,age=20,gender=1})'>查看學員詳情</a> //路由規則 routes.MapRoute( name: "Test1", url: "{controller}/{action}/{id}/{age}/{gender}", defaults: new { controller = "Home", action = "Index", id = 10 } ); //生成的a標簽 <a href="/Student/StudentDetail/1001/20/1">查看學員詳情</a> //遍歷RouteData.values結果如下 controller:Student action:StudentDetail id:1001 age:20 gender:1