ASP.NET MVC路由扩展:链接和URL的生成(2)

来源:未知 责任编辑:责任编辑 发表时间:2014-02-02 17:48 点击:

  19: }
由于HtmlHelper只要在View中使用,所以它具有一个通过ViewContext属性表示的针对View的上下文。至于该属性对应的类型ViewContext,它是表示Controller上下文的ControllerContext的子类,而后者通过RequestContext和RouteData属性提供当前的请求上下文和路由数据(其实RouteData属性表示的RouteData对象已经包含在RequestContext属性表示的RequestContext对象中)。
二、UrlHelper.Action V.S. HtmlHelper.ActionLink
UrlHelper和HtmlHelper分别通过Action和ActionLink方法用于生成一个针对某个Controller的某个Action的URL和链接。下面的代码片断列出了UrlHelper的所有Action重载,参数actionName和controllerName分别代表Action和Controller的名称。通过object或者RouteValueDictionary类型表示的routeValues参数表示替换URL模板中变量的变量值。参数protocol和hostName代表作为完整URL的传输协议(比如http和https等)以及主机名。
   1: public class UrlHelper
   2: {
   3:     //其他成员
   4:     public string Action(string actionName);
   5:     public string Action(string actionName, object routeValues);
   6:     public string Action(string actionName, string controllerName);
   7:     public string Action(string actionName, RouteValueDictionary routeValues);
   8:     public string Action(string actionName, string controllerName, object routeValues);
   9:     public string Action(string actionName, string controllerName, RouteValueDictionary routeValues);
  10: 
  11:     public string Action(string actionName, string controllerName, object routeValues, string protocol);
  12:     public string Action(string actionName, string controllerName, RouteValueDictionary routeValues, string protocol, string hostName);
  13: }
对于定义在UrlHelper中的众多Action方法,如果我们显示指定了传输协议(protocol参数)或者主机名称,返回的是一个完整的URL;否则返回的是一个相对URL。如果我们没有显示地指定Controller的名称(controllerName参数),那么当前Controller的名称被采用。对于UrlHelper来说,通过RequestContext属性表示的当前请求上下文包含了相应的路由信息,即RequestContext的RouteData属性表示的RouteData。RouteData的Values属性中必须包含一个Key为“controller”的元素,其值就代表当前Controller的名称。
在System.Web.Mvc.Html.LinkExtensions中,我们为HtmlHelper定义了如下所示的一系列ActionLink方法重载。顾名思义,ActionLink不再仅仅返回一个URL,而是生成一个链接(<a>...</a>),但是其中作为目标URL的生成逻辑和UriHelper是完全一致的。
   1: public static class LinkExtensions
   2: {
   3:     //其他成员
   4:     public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName);
   5:     public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • 浅析.NET下XML数据访问新机制
  • asp.net 面试+笔试题目第1/2页
  • C# 邮件地址是否合法的验证
  • asp.net 设置GridView的选中行的实现代码
  • C#高级编程:数据库连接[1]
  • 经典C++程序1
  • IIS 自动回收导致后台定时器失效的问题解决
  • ASP.NET&#160;GridView列表代码示例
  • Asp.net MVC源码分析--Action Filter的链式调用
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1