2016-11-16 95 views
0

我正在尝试为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); 
    } 
+0

'返回htmlHelper.EditorFor (表达式,ViewData)'不添加任何属性。它只是使用传递给方法 –

+0

的原始'ViewData'属性如何编辑并返回属性?我无法返回新的viewData对象,因为它是不同的类型 – user3208483

回答

0

你的方法参数,而不是自定义HTML返回原ViewData属性的属性集合。从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

HTML.EditorFor adding class not working

+0

EditorFor()方法不接受其第2个参数中的html属性 –