以下是解决方案 -
感谢这位杰出的绅士ThumNet,他编写了一个将枚举转换为RadioButtonList的扩展程序
步骤1 - 在 Views/Shared/EditorTemplates 目录下创建 RadioButtonListEnum.cshtml 文件,并添加以下代码(代码来自上述参考链接)-
@model Enum
@{
Func<Enum, string> getDescription = en =>
{
Type type = en.GetType();
System.Reflection.MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute),
false);
if (attrs != null && attrs.Length > 0)
return ((System.ComponentModel.DataAnnotations.DisplayAttribute)attrs[0]).GetName();
}
return en.ToString();
};
var listItems = Enum.GetValues(Model.GetType()).OfType<Enum>().Select(e =>
new SelectListItem()
{
Text = getDescription(e),
Value = e.ToString(),
Selected = e.Equals(Model)
});
string prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
int index = 0;
ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;
foreach (var li in listItems)
{
string fieldName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_{1}", prefix, index++);
<div class="editor-radio">
@Html.RadioButton(prefix, li.Value, li.Selected, new { @id = fieldName })
@Html.Label(fieldName, li.Text)
</div>
}
ViewData.TemplateInfo.HtmlFieldPrefix = prefix;
}
那么请定义您的枚举 -
public enum QuestionEnd
{
[Display(Name = "Cancel Invitation")]
CancelInvitation,
[Display(Name = "Plan with participants on first available common date")]
FirstAvailableCommon,
[Display(Name = "Plan with participants on my first available common date")]
YourFirstAvailableCommon
}
第二步 - 创建模型 -
public class RadioEnumModel
{
public QuestionEnd qEnd { get; set; }
}
步骤 3 - 创建控制器动作 -
public ActionResult Index()
{
RadioEnumModel m = new RadioEnumModel();
return View(m);
}
第四步 - 创建视图 -
@model MVC.Controllers.RadioEnumModel
@Html.EditorFor(x => x.qEnd, "RadioButtonListEnum")
那么输出结果将是 -
![enter image description here](https://istack.dev59.com/zKP5K.webp)