MVC 路由-->链接

链接的地址,可以根据路由规则动态生成,不用写死,文档结构有变化时,依然可以找到正确的路径

1.url.Action(只生成URL)

   有很多重载方法,可以根据需要选择,生成URL时,会根据路由规则生成,不过调用时也是根据路由规则寻址,所以OK

   

<a href="@Url.Action("GetStuDetail","Student",new {id=1001,gender=1})">学员详情</a>
//路由规则

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

//匹配结果
<a href="/Student/GetStuDetail/1001?gender=1">学员详情</a>

2.Html.ActionLink(生成整个Link标签)

//View页面生成标签 
@Html.ActionLink("新增学员", "AddNewStu", "Student",
 new { gender = 1, age = 10, name = "李磊" },  //Url参数
new { @class="AddStuLink",title="新增学员"})    //Html标签属性

//路由规则

  routes.MapRoute(
             name: "Test1",
             url: "{action}/{controller}",
             defaults: new { controller = "Home", action = "Index" }
  )

//生成的链接
<a title="新增学员" class="AddStuLink" href="/AddNewStu/Student?gender=1&age=10&name=%E6%9D%8E%E7%A3%8A">新增学员</a>

 标签根据路由规则生成URL,所以,action在前,controller在后,路由中对要求必须有Controller和action,但位置不做要求,可以起到一定的屏蔽作用

 注意 url的生成与路由表息息相关,路由规则变化后,url对应变化,路由表不可随意变更

 以上两种方法只匹配路由表中第一条路由(controller和action) url有的,作为路由,没有的作为参数。

 

 

<a href='@Url.Action("StudentDetail","Student",new {id=1001,age=20,gender=1})'>查看学员详情</a>

//路由规则1
   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>  //其他的作为参数


//路由规则2 
   routes.MapRoute(
            name: "Test1",
            url: "{controller}/{action}/{id}/{age}/{gender}",
            defaults: new { controller = "Home", action = "Index", id = 10 } 
        );
//生成的链接  
<a href="/Student/StudentDetail/1001/20/1">查看学员详情</a>   //匹配到,作为路由

 

posted @ 2017-12-02 10:52  C小小  阅读(403)  评论(0编辑  收藏  举报