路由数据 RouteData.Values[key]

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&amp;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

 

posted @ 2017-12-02 13:18  C小小  阅读(4555)  评论(0编辑  收藏  举报