Enum RadioButtonFor Editor Template set value

回眸只為那壹抹淺笑 提交于 2019-12-02 09:53:36

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)

you can change like this in your view

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

and submit your form

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