我正在为 ASP.NET MVC 编写自己的 HtmlHelper 扩展:
public static string CreateDialogLink (this HtmlHelper htmlHelper, string linkText,
string contentPath)
{
// fix up content path if the user supplied a path beginning with '~'
contentPath = Url.Content(contentPath); // doesn't work (see below for why)
// create the link and return it
// .....
};
我遇到麻烦的地方是尝试UrlHelper
从我的 HtmlHelper 的定义中访问。问题是您通常访问HtmlHelper
(通过Html.MethodName(...)
)的方式是通过视图上的属性。这显然不适用于我自己的扩展类。
这是ViewMasterPage
(截至 Beta 版)的实际 MVC 源代码 - 它定义Html
和Url
.
public class ViewMasterPage : MasterPage
{
public ViewMasterPage();
public AjaxHelper Ajax { get; }
public HtmlHelper Html { get; }
public object Model { get; }
public TempDataDictionary TempData { get; }
public UrlHelper Url { get; }
public ViewContext ViewContext { get; }
public ViewDataDictionary ViewData { get; }
public HtmlTextWriter Writer { get; }
}
我希望能够在 HtmlHelper 中访问这些属性。
我想出的最好的就是这个(在CreateDialogLink
方法的开头插入)
HtmlHelper Html = new HtmlHelper(htmlHelper.ViewContext, htmlHelper.ViewDataContainer);
UrlHelper Url = new UrlHelper(htmlHelper.ViewContext.RequestContext);
我是否错过了访问现有实例HtmlHelper
和UrlHelper
实例的其他方式 - 还是我真的需要创建一个新实例?我敢肯定没有太多开销,但如果可以的话,我更愿意使用预先存在的开销。