基于this问题,我实现了一个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(enum)以便选择单选按钮?
答案 0 :(得分:3)
您可以创建一个自定义html帮助程序,它将提供双向绑定
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());
}
}
}
添加对web.config
的<namespaces>
部分的引用
<add namespace="YourAssembly.Html "/>
并将其用作
@Html.EnumRadioButtonListFor(m => m.QuestionResponse)
答案 1 :(得分:0)
您可以在视图中更改
<input type="checkbox" id="checkbox1" name="checkbox" class="checkBoxId" value="@Model.checkbox"/>
并提交表单