我正在尝试为自定义日期格式实现自定义 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
使用
关于c# - ASP.Net MVC - 无法识别 'this HtmlHelper',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34876497/