Reputation: 8477
Based on this question, I implemented a RadioButtonFor Editor Template. I works great but currently you cannot pass the value you want selected.
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())
}
}
I call it from View with:
@Html.EditorFor(m => m.QuestionResponse, "EnumRadioButtonList")
How do I pass the value QuestionResponse (enum) so that the radio button is selected?
Upvotes: 0
Views: 869
Reputation:
You can create a custom html helper which will give 2-way binding
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());
}
}
}
add a reference to the <namespaces>
section of web.config
<add namespace="YourAssembly.Html "/>
and use it as
@Html.EnumRadioButtonListFor(m => m.QuestionResponse)
Upvotes: 3
Reputation: 1
you can change like this in your view
<input type="checkbox" id="checkbox1" name="checkbox" class="checkBoxId" value="@Model.checkbox"/>
and submit your form
Upvotes: 0