2017-06-19 57 views
0

MVC的EnumDropDownListFor html幫助器不會呈現Description和ShortName屬性。我需要渲染選項標籤的自定義屬性文本。我搜查了很多不是重寫MVC中的所有內容,但我找不到任何內容。Enumdropdownlist用於擴展描述和短名稱字段

我知道MVC與WebForms不同,但MVC應該提供了一種自定義渲染機制的方法。

回答

0

基於我的搜索,我首先需要讀取Enum類型的所有成員,然後重寫包含驗證的渲染機制。修改基本方法的html最糟糕的選擇是使用正則表達式。結果代碼如下:

public static MvcHtmlString EnumDropDownListForEx<T, TProperty>(this HtmlHelper<T> htmlHelper, Expression<Func<T, TProperty>> expression, 
     object htmlAttributes, string placeholder = "") 
    { 
     var type = Nullable.GetUnderlyingType(typeof(TProperty)) ?? typeof(TProperty); 
     var values = Enum.GetValues(type); 

     var name = ExpressionHelper.GetExpressionText(expression); 
     var fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); 

     var select = new TagBuilder("select"); 
     select.MergeAttribute("name", fullHtmlFieldName); 
     select.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 

     var option = new TagBuilder("option"); 
     option.MergeAttribute("value", ""); 
     option.MergeAttribute("selected", "selected"); 
     option.InnerHtml = placeholder; 

     var sb = new StringBuilder(); 
     sb.Append(option.ToString(TagRenderMode.Normal)); 

     foreach (Enum value in values) 
     { 
      option = new TagBuilder("option"); 
      option.MergeAttribute("value", value.ToInt().ToString()); 
      option.InnerHtml = value.GetEnumDescription(); 

      var attr = value.GetAttribute<DisplayAttribute>(); 
      if(attr == null) 
       continue; 

      option.InnerHtml = attr.Name; 
      option.MergeAttribute("description", attr.Description); 
      option.MergeAttribute("shortname", attr.ShortName); 
      sb.Append(option.ToString(TagRenderMode.Normal)); 
     } 

     select.InnerHtml = sb.ToString(); 
     select.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name)); 

     return MvcHtmlString.Create(select.ToString(TagRenderMode.Normal)); 
    }