我正在使用另一个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());
}
}
}
与我当前的enum
:
public enum Options
{
[Display(Name ="Yes")]
0,
[Display(Name = "No")]
1,
[Display(Name = "Other")]
2,
}
如果我然后使用@html.RadioButtonForEnum(...)
它显示我的枚举,选中相应的框没问题。但是,我希望他们使用标签值[Display(Name = "<text>")]
,这样他们就更有意义了! - 即不只是0,1,2。
答案 0 :(得分:12)
您可以使用反射来获取值:
public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, 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}",
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(label),
radio
);
}
return MvcHtmlString.Create(sb.ToString());
}
答案 1 :(得分:0)
您可能需要枚举的扩展方法来获取您在枚举选项中放置的显示属性。 然后,当您在RadioButtonForEnum方法中获取选项枚举值的名称或值时,您只需调用extensions方法来填充该值。
我最近撰写了一篇关于此主题的博文:http://joerijans.blogspot.com/2011/10/triple-door-extension-method-custom.html
希望这有帮助。
答案 2 :(得分:0)
我在代码中使用[Description]
,但您可以将其更改为使用DisplayAttribute
: