Enum RadioButtonFor Editor Template设置值

基于这个问题,我实现了一个RadioButtonFor编辑器模板。 我工作得很好,但目前你无法传递你想要的价值。

EnumRadioButtonList.cshtml (Editor Template): @model Enum @foreach (var value in Enum.GetValues(Model.GetType())) { if ((int)value > 0) { @Html.RadioButtonFor(m => m, (int)value) @Html.Label(value.ToString()) } } 

我从View中调用它:

 @Html.EditorFor(m => m.QuestionResponse, "EnumRadioButtonList") 

如何传递值QuestionResponse(枚举)以便选择单选按钮?

您可以创建一个自定义html帮助程序,它将提供双向绑定

 namespace YourAssembly.Html { public static class EnumHelpers { public static MvcHtmlString EnumRadioButtonListFor(this HtmlHelper helper, Expression> expression) { ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); string name = ExpressionHelper.GetExpressionText(expression); if (!metaData.ModelType.IsEnum) { throw new ArgumentException(string.Format("The property {0} is not an enum", name)); } string[] names = Enum.GetNames(metaData.ModelType); StringBuilder html = new StringBuilder(); foreach(string value in names) { string id = string.Format("{0}_{1}", name, value); html.Append("
"); html.Append(helper.RadioButtonFor(expression, value, new { id = id })); html.Append(helper.Label(id, value)); html.Append("
"); } return MvcHtmlString.Create(html.ToString()); } } }

添加对web.config的部分的引用

  

并用它作为

 @Html.EnumRadioButtonListFor(m => m.QuestionResponse) 

你可以在你的视图中这样改变

  

并提交表格