我正在为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
(via Html.MethodName(...)
)的方式是通过View上的属性.我自己的扩展课程显然无法使用此功能.
这是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
实例的其他方式- 或者我真的需要创建一个新方法吗?我确信没有太多开销,但如果可以,我宁愿使用已有的那些.
在问这个问题之前我曾经看过一些MVC源代码,但显然我错过了这个,这就是他们为Image helper做的.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters")] public static string Image(this HtmlHelper helper, string imageRelativeUrl, string alt, IDictionaryhtmlAttributes) { if (String.IsNullOrEmpty(imageRelativeUrl)) { throw new ArgumentException(MvcResources.Common_NullOrEmpty, "imageRelativeUrl"); } UrlHelper url = new UrlHelper(helper.ViewContext); string imageUrl = url.Content(imageRelativeUrl); return Image(imageUrl, alt, htmlAttributes).ToString(TagRenderMode.SelfClosing); }
看起来像实例化一个新UrlHelper
的毕竟是正确的方法.这对我来说足够好了.
更新:ASP.NET MVC v1.0源代码中的 RTM代码略有不同,如注释中所述.
文件:MVC\src\MvcFutures\Mvc\ImageExtensions.cs
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters")] public static string Image(this HtmlHelper helper, string imageRelativeUrl, string alt, IDictionaryhtmlAttributes) { if (String.IsNullOrEmpty(imageRelativeUrl)) { throw new ArgumentException(MvcResources.Common_NullOrEmpty, "imageRelativeUrl"); } UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext); string imageUrl = url.Content(imageRelativeUrl); return Image(imageUrl, alt, htmlAttributes).ToString(TagRenderMode.SelfClosing); }