Using [Display(Name = “X”)] with an enum. Custom HtmlHelper in MVC3 ASP.Net

前端 未结 3 2538
余生分开走
余生分开走 2021-02-20 16:31

Im using a snippet of code from another stackoverflow question:

namespace MvcHtmlHelpers
{
    public static class htmlHelpers
    {
        /// 
         


        
3条回答
  •  半阙折子戏
    2021-02-20 16:57

    You could use reflection to fetch the value:

    public static MvcHtmlString RadioButtonForEnum(
        this HtmlHelper htmlHelper,
        Expression> expression
    )
    {
        var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    
        var sb = new StringBuilder();
        var enumType = metaData.ModelType;
        foreach (var field in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
        {
            var value = (int)field.GetValue(null);
            var name = Enum.GetName(enumType, value);
            var label = name;
            foreach (DisplayAttribute currAttr in field.GetCustomAttributes(typeof(DisplayAttribute), true))
            {
                label = currAttr.Name;
                break;
            }
    
            var id = string.Format(
                "{0}_{1}_{2}",
                htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
                metaData.PropertyName,
                name
            );
            var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();
            sb.AppendFormat(
                " {2}",
                id,
                HttpUtility.HtmlEncode(label),
                radio
            );
        }
        return MvcHtmlString.Create(sb.ToString());
    }
    

提交回复
热议问题