[英]MVC EditorFor Custom Helper
我正在嘗試為EditorFor創建自定義幫助器。 我想從模型中獲取字符串長度,並將其添加到html屬性中。
到目前為止,我有以下內容,但這並不適用添加的新屬性。
public static IHtmlString MyEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object ViewData, bool disabled = false, bool visible = true)
{
var member = expression.Body as MemberExpression;
var stringLength = member.Member.GetCustomAttributes(typeof(StringLengthAttribute), false).FirstOrDefault() as StringLengthAttribute;
RouteValueDictionary viewData = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData);
RouteValueDictionary htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(viewData["htmlAttributes"]);
if (stringLength != null)
{
htmlAttributes.Add("maxlength", stringLength.MaximumLength);
}
return htmlHelper.EditorFor(expression, ViewData);
}
您將在方法參數中返回原始ViewData
屬性,而不是在return htmlHelper.EditorFor(expression, ViewData)
上return htmlHelper.EditorFor(expression, ViewData)
自定義HTML屬性集合。 根據此答案 ,您的return方法應更改為:
public static IHtmlString MyEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object ViewData, bool disabled = false, bool visible = true)
{
var member = expression.Body as MemberExpression;
var stringLength = member.Member.GetCustomAttributes(typeof(StringLengthAttribute), false).FirstOrDefault() as StringLengthAttribute;
RouteValueDictionary viewData = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData);
RouteValueDictionary htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(viewData["htmlAttributes"]);
if (stringLength != null)
{
htmlAttributes.Add("maxlength", stringLength.MaximumLength);
}
return htmlHelper.EditorFor(expression, htmlAttributes); // use custom HTML attributes here
}
然后,在視圖側應用自定義HTML幫助器,如下所示:
@Html.MyEditorFor(model => model.Property, new { htmlAttributes = new { @maxlength = "10" }})
編輯 :
此方法適用於MVC 5(5.1)及更高版本,我無法確定它是否適用於早期版本(請參閱此問題: ASP.NET MVC中EditorFor()的HTML屬性 )。
對於早期的MVC版本,更優選使用HtmlHelper.TextBoxFor
,它當然具有maxlength
屬性:
return htmlHelper.TextBoxFor(expression, htmlAttributes);
其他參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.