【问题标题】:Enum RadioButtonFor Editor Template set value枚举 RadioButtonFor 编辑器模板设置值
【发布时间】:2015-03-15 02:49:30
【问题描述】:

基于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) 以便选择单选按钮?

【问题讨论】:

    标签: c# asp.net-mvc radio-button asp.net-mvc-5 mvc-editor-templates


    【解决方案1】:

    您可以创建一个自定义的 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());
        }
      }
    }
    

    添加对 web.config 的 &lt;namespaces&gt; 部分的引用

    <add namespace="YourAssembly.Html "/>
    

    并将其用作

    @Html.EnumRadioButtonListFor(m => m.QuestionResponse)
    

    【讨论】:

      【解决方案2】:

      你可以在你的视图中这样改变

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

      并提交您的表单

      【讨论】:

      • 这对我不起作用,因为我不想管理 ID。这是列表的一部分,所以不止一个。
      • 您可以在我测试之前创建一个列表并输入输入,它适用于 foreach (var item in list) { }
      • 使用编辑器模板的好处之一是它可以管理 id,创建输入标签意味着我需要管理 Id。
      猜你喜欢
      • 2012-01-11
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多