我正在尝试为EditorFor创建一个自定义帮助器。我想从模型中获取字符串长度并将其添加到html属性中。MVC EditorFor自定义帮助器
到目前为止我有以下内容,但是这并不适用添加的新属性。在return htmlHelper.EditorFor(expression, ViewData)
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);
}
'返回htmlHelper.EditorFor (表达式,ViewData)'不添加任何属性。它只是使用传递给方法 –
的原始'ViewData'属性如何编辑并返回属性?我无法返回新的viewData对象,因为它是不同的类型 – user3208483