mvc中Url.RouteUrl或者Html.RouteLink实现灵活超链接,使href的值随路由名称或配置的改变而改变
Posted on 2014-04-22 17:26 weekzero 阅读(1642) 评论(0) 编辑 收藏 举报mvc,超链接除了直接写在a标签的href内还可以使用路由规则来生成,这样在改变了路由规则或者路由名称时不用再去代码中更改href的值,而且还容易遗漏。借助Url.RouteUrl或者Html.RouteLink就可以轻松实现,再以后的改变中将不用再去理会路由规则的改变而带来的工作量。
路由规则:
//bubuko测试 routes.MapRoute("bubuko_1", "{controller}-{action}-{eID}-{pageIndex}.html", new { controller = "abc", action = "Index" }); //bubuko测试 routes.MapRoute("bubuko_2", "{action}-{eID}-{pageIndex}.html", new { controller = "abc", action = "Index" });
cshtml中代码:
Url.RouteUrl方式,路由名称是“bubuko_1”:@Url.RouteUrl("bubuko_1", new { eID = ViewBag.eID, pageIndex = ViewBag.pageIndex }) <br /> Url.RouteUrl方式,路由名称是“bubuko_2”:@Url.RouteUrl("bubuko_2", new { eID = ViewBag.eID, pageIndex = ViewBag.pageIndex }) <br /> <br /> Html.RouteLink方式,路由名称是“bubuko_1”:@Html.RouteLink("bubuko.com分享超链接", "bubuko_1", new { eID = ViewBag.eID, pageIndex = ViewBag.pageIndex }, new { id = "abc" }) <br /> Html.RouteLink方式,路由名称是“bubuko_2”:@Html.RouteLink("bubuko.com分享超链接", "bubuko_2", new { eID = ViewBag.eID, pageIndex = ViewBag.pageIndex }, new { id = "abc" })
显示效果,html代码:
Url.RouteUrl方式,路由名称是“bubuko_1”:/abc-abclist-10-12.html <br /> Url.RouteUrl方式,路由名称是“bubuko_2”:/abclist-10-12.html <br /> <br /> Html.RouteLink方式,路由名称是“bubuko_1”:<a href="/abc-abclist-10-12.html" id="abc">bubuko.com分享超链接</a> <br /> Html.RouteLink方式,路由名称是“bubuko_2”:<a href="/abclist-10-12.html" id="abc">bubuko.com分享超链接</a>