我正在尝试为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);
}
答案 0 :(得分:0)
您将在方法参数中返回原始ViewData
属性,而不是return htmlHelper.EditorFor(expression, ViewData)
上的自定义HTML属性集合。基于this answer,您的返回方法应更改为:
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)及更高版本,我不能确定它是否适用于早期版本(请参阅此问题:Html attributes for EditorFor() in ASP.NET MVC)。
对于早期的MVC版本,更优先使用HtmlHelper.TextBoxFor
,当然具有maxlength
属性:
return htmlHelper.TextBoxFor(expression, htmlAttributes);
其他参考资料:
Set the class attribute to Html.EditorFor in ASP.NET MVC Razor View