Skip to main content
 首页 » 编程设计

c#之ASP.Net MVC之无法识别 'this HtmlHelper'

2024年02月05日12emanlee

我正在尝试为自定义日期格式实现自定义 HtmlHelper。
(因为 TextBoxFor 忽略了日期格式属性,而 EditorFor 忽略了类,但这不是问题所在)
这是自定义的 HtmlHelper:

namespace SigmaAdminCore.MyHtmlHelpers 
{ 
    public static class MyHtmlHelpers 
    { 
        public static MvcHtmlString MyDateFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) 
        { 
            var mvcHtmlString = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, new { @class = "text-box single-line date-picker" }); 
            var xDoc = XDocument.Parse(mvcHtmlString.ToHtmlString()); 
            var xElement = xDoc.Element("input"); 
            if (xElement != null) 
            { 
                var valueAttribute = xElement.Attribute("value"); 
                if (valueAttribute != null) 
                { 
                    valueAttribute.Value = DateTime.Parse(valueAttribute.Value).ToShortDateString(); 
                    if (valueAttribute.Value == "1/1/0001") 
                        valueAttribute.Value = string.Empty; 
                } 
            } 
            return new MvcHtmlString(xDoc.ToString()); 
        } 
    } 
} 

在我看来我有:

@using SigmaAdminCore.MyHtmlHelpers 
... 
@MyHtmlHelpers.MyDateFor(model => model.ExpirationDate) 

这里是错误:

There is no argument given that corresponds to the required formal parameter 'expression' of 'MyHtmlHelpers.MyDateFor(HtmlHelper, Expression>)'

我的猜测是 ASP 不会替换 this HtmlHelper<TModel> htmlHelper按正确的值或不知道如何。尽管MyDateFor方法与 TextBoxFor 具有相同的签名InputExtensions.cs 中定义的方法:

public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) 

请您参考如下方法:

行:

@MyHtmlHelpers.MyDateFor(model => model.ExpirationDate) 

应该是:

@Html.MyDateFor(model => model.ExpirationDate) 

因为你扩展了this HtmlHelper<TModel> .


基本上是 this HtmlHelper<TModel> htmlHelper 行使其成为 HtmlHelper<TModel> 的扩展方法.
“在幕后”cshtml 文件的类型是 WebViewPage<TModel>上面有这条线:

public HtmlHelper<TModel> Html { get; set; } 

这使得您的扩展方法可以通过 @html 使用