我使用另一个stackoverflow问题的一段代码:
namespace MvcHtmlHelpers { public static class htmlHelpers { /// <summary> /// Radio button for : Adapted to support enum labels from display attributes /// </summary> /// <typeparam name="TModel"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="htmlHelper"></param> /// <param name="expression"></param> /// <returns></returns> public static MvcHtmlString RadioButtonForEnum<TModel,TProperty>( this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel,TProperty>> expression ) { var MetaData = ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData); var names = Enum.GetNames(MetaData.ModelType); var sb = new StringBuilder(); foreach (var name in names) { 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( "<label for=\"{0}\">{1}</label> {2}",id,HttpUtility.HtmlEncode(name),radio ); } return MvcHtmlString.Create(sb.ToString()); } } }
沿着我目前的枚举:
public enum Options { [Display(Name ="Yes")] 0,[Display(Name = "No")] 1,[Display(Name = "Other")] 2,}
如果我然后使用@ html.RadioButtonForEnum(…)它显示我的枚举与相应的框选择没有问题.但是,我希望他们使用标签值[Display(Name =“< text>”)],以使它们更有意义!即不仅仅是0,1,2.
解决方法
您可以使用反射来获取值:
public static MvcHtmlString RadioButtonForEnum<TModel,TProperty>( this HtmlHelper<TModel> htmlHelper,TProperty>> 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}",name ); var radio = htmlHelper.RadioButtonFor(expression,new { id = id }).ToHtmlString(); sb.AppendFormat( "<label for=\"{0}\">{1}</label> {2}",HttpUtility.HtmlEncode(label),radio ); } return MvcHtmlString.Create(sb.ToString()); }