2016-11-16 121 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屬性 –

相關問題