基于this https://stackoverflow.com/questions/18542060/mvc4-enum-and-radio-button-list问题,我实现了一个 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 帮助器,它将提供 2 路绑定
namespace YourAssembly.Html
{
public static class EnumHelpers
{
public static MvcHtmlString EnumRadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> 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("<div>");
html.Append(helper.RadioButtonFor(expression, value, new { id = id }));
html.Append(helper.Label(id, value));
html.Append("</div>");
}
return MvcHtmlString.Create(html.ToString());
}
}
}
添加对的引用<namespaces>
web.config 部分
<add namespace="YourAssembly.Html "/>
并将其用作
@Html.EnumRadioButtonListFor(m => m.QuestionResponse)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)