2017-06-19 3 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)); 
    } 
関連する問題