【发布时间】:2016-11-16 11:37:15
【问题描述】:
我正在尝试为 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);
}
【问题讨论】:
-
return htmlHelper.EditorFor(expression, ViewData)没有添加任何属性。它只是使用您传递给方法的原始ViewData属性 -
如何编辑它并返回属性?我无法返回新的 viewData 对象,因为它是不同的类型
标签: c# asp.net-mvc editorfor