【问题标题】:ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC具有强绑定模型 MVC 的 ASP.NET MVC 是/否单选按钮
【发布时间】:2011-02-03 06:59:29
【问题描述】:

有谁知道如何将“是/否”单选按钮绑定到 ASP.NET MVC 中强类型模型的布尔属性。

型号

public class MyClass
{
     public bool Blah { get; set; }
}

查看

<%@  Page Title="blah"  Inherits="MyClass"%>
    <dd>
        <%= Html.RadioButton("blah", Model.blah) %> Yes
        <%= Html.RadioButton("blah", Model.blah) %> No
    </dd>

谢谢

解决方案:

感谢 Brian 的指导,但这与他所写的相反。就这样——

<%@  Page Title="blah"  Inherits="MyClass"%>
<dd>
    <%= Html.RadioButton("blah", !Model.blah) %> Yes
    <%= Html.RadioButton("blah", Model.blah) %> No
</dd>

【问题讨论】:

  • 这些解决方案的“问题”(我在我的项目中使用了 Ben Cull 风格)是你不能用它们做标签。两个单选按钮输入将具有相同的 id 和名称,因此如果您使用 Html.LabelFor,它将链接到 DOM 中具有该 id 的第一个单选按钮输入。就像我说的那样,我正在使用单选按钮的这种解决方案来表示布尔字段,我只是想让人们知道标签会有点不稳定。
  • 查看 Jeff Bobish 的回答,了解如何优雅地解决标签问题。

标签: c# asp.net-mvc model radio-button boolean


【解决方案1】:

如果您使用的是 MVC 3 和 Razor,您还可以使用以下内容:

@Html.RadioButtonFor(model => model.blah, true) Yes
@Html.RadioButtonFor(model => model.blah, false) No

【讨论】:

    【解决方案2】:

    第二个参数被选中,所以使用 !当布尔值为 false 时选择 no 值。

    <%= Html.RadioButton("blah", !Model.blah) %> Yes 
    <%= Html.RadioButton("blah", Model.blah) %> No 
    

    【讨论】:

      【解决方案3】:

      这是一个更完整的示例,出于可访问性原因使用fieldset 并将第一个按钮指定为默认按钮。如果没有fieldset,则无法以编程方式确定单选按钮整体的用途。

      型号

      public class MyModel
      {
          public bool IsMarried { get; set; }
      }
      

      查看

      <fieldset>
          <legend>Married</legend>
      
          @Html.RadioButtonFor(e => e.IsMarried, true, new { id = "married-true" })
          @Html.Label("married-true", "Yes")
      
          @Html.RadioButtonFor(e => e.IsMarried, false, new { id = "married-false" })
          @Html.Label("married-false", "No")
      </fieldset>
      

      您可以向匿名对象添加@checked 参数以将单选按钮设置为默认值:

      new { id = "married-true", @checked = 'checked' }
      

      请注意,您可以通过将 truefalse 替换为字符串值来绑定到字符串。

      【讨论】:

      • 你应该实际使用 new { id = Html.Id("married-true") },减少生成的 id 前缀的潜在范围问题。
      【解决方案4】:

      根据 Ben 的回答,我添加了 ID 的属性,以便可以使用标签。

      <%: Html.Label("isBlahYes", "Yes")%><%= Html.RadioButtonFor(model => model.blah, true, new { @id = "isBlahYes" })%>
      <%: Html.Label("isBlahNo", "No")%><%= Html.RadioButtonFor(model => model.blah, false, new { @id = "isBlahNo" })%>
      

      我希望这会有所帮助。

      【讨论】:

      • 标签通常位于单选按钮之后。
      • 在单选按钮周围放置标签是完全有效的。
      【解决方案5】:

      使用常规 HTML 在单选按钮周围添加标签标签也可以解决“labelfor”问题:

      <label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
      <label><%= Html.RadioButton("blah", Model.blah) %> No</label>
      

      现在单击文本会选择相应的单选按钮。

      【讨论】:

        【解决方案6】:

        或 MVC 2.0:

        <%= Html.RadioButtonFor(model => model.blah, true) %> Yes
        <%= Html.RadioButtonFor(model => model.blah, false) %> No
        

        【讨论】:

          【解决方案7】:

          如果我可以把帽子扔进戒指,我认为有一种比现有答案更简洁的方法来重用单选按钮功能。

          假设您的 ViewModel 中有以下属性:

          Public Class ViewModel
              <Display(Name:="Do you like Cats?")>
              Public Property LikesCats As Boolean
          End Class
          

          您可以通过可重复使用的editor template 公开该属性:

          首先,创建文件Views/Shared/EditorTemplates/YesNoRadio.vbhtml

          然后将以下代码添加到YesNoRadio.vbhtml

          @ModelType Boolean?
          
          <fieldset>
              <legend>
                  @Html.LabelFor(Function(model) model)
              </legend>
          
              <label>
                  @Html.RadioButtonFor(Function(model) model, True) Yes
              </label>
              <label>
                  @Html.RadioButtonFor(Function(model) model, False) No
              </label>
          </fieldset>
          

          您可以通过在视图中手动指定模板名称来调用属性的编辑器:

          @Html.EditorFor(Function(model) model.LikesCats, "YesNoRadio")
          

          优点:

          • 开始在 HTML 编辑器中编写 HTML,而不是在后面的代码中附加字符串。
          • 保留 DisplayName DataAnnotation
          • 允许点击标签来切换单选按钮
          • 在表单中维护的代码最少(1 行)。如果渲染方式有问题,请使用模板处理。

          【讨论】:

          • 这很好,但是布尔值的第三个选项呢? @Html.RadioButtonFor(Function(Model) Model.IsVerified, True) Yes @Html.RadioButtonFor(Function(Model) Model.IsVerified, False) No @Html.RadioButtonFor (Function(Model) Model.IsVerified, Nothing)) 待处理
          【解决方案8】:

          我最终将它打包成一个扩展方法,这样 (1) 我可以立即生成标签和收音机 (2) 所以我不必大惊小怪地指定自己的 ID:

          public static class HtmlHelperExtensions
          {
              public static MvcHtmlString RadioButtonAndLabelFor<TModel, TProperty>(this HtmlHelper<TModel> self, Expression<Func<TModel, TProperty>> expression, bool value, string labelText)
              {
                  // Retrieve the qualified model identifier
                  string name = ExpressionHelper.GetExpressionText(expression);
                  string fullName = self.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
          
                  // Generate the base ID
                  TagBuilder tagBuilder = new TagBuilder("input");
                  tagBuilder.GenerateId(fullName);
                  string idAttr = tagBuilder.Attributes["id"];
          
                  // Create an ID specific to the boolean direction
                  idAttr = String.Format("{0}_{1}", idAttr, value);
          
                  // Create the individual HTML elements, using the generated ID
                  MvcHtmlString radioButton = self.RadioButtonFor(expression, value, new { id = idAttr });
                  MvcHtmlString label = self.Label(idAttr, labelText);
          
                  return new MvcHtmlString(radioButton.ToHtmlString() + label.ToHtmlString());
              }
          }
          

          用法:

          @Html.RadioButtonAndLabelFor(m => m.IsMarried, true, "Yes, I am married")
          

          【讨论】:

            猜你喜欢
            • 2011-07-20
            • 1970-01-01
            • 1970-01-01
            • 2011-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多