Enum RadioButtonFor Editor Template set value

别说谁变了你拦得住时间么 提交于 2019-12-31 07:01:10

问题


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?


回答1:


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)



回答2:


you can change like this in your view

<input type="checkbox" id="checkbox1" name="checkbox" class="checkBoxId" value="@Model.checkbox"/>

and submit your form



来源:https://stackoverflow.com/questions/27984973/enum-radiobuttonfor-editor-template-set-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!