【问题标题】:ASP.NET MVC and multiple checkboxes for several properties, how to do that?ASP.NET MVC 和多个属性的多个复选框,该怎么做?
【发布时间】:2012-12-12 05:59:30
【问题描述】:

我有这样的事情:

public class MyClass
{
    public int Id {get;set;}
    public bool First {get;set;}
    public bool Second {get;set;}
    public bool Third {get;set;}
}

现在,我想生成一些东西,它会显示这个:

First - [checkbox] 
Second - [checkbox] 
Third - [checkbox]
[Submit]

我希望这些复选框从这些属性中只选择一项,我该怎么做?

编辑:对不起,我真的不需要复选框,我需要的是单选按钮。如果有人有任何示例代码显示如何使用单选按钮解决我的问题,我将不胜感激。

【问题讨论】:

  • 互斥复选框在任何 HTML 框架中都不是标准的。您应该使用 javascript 来实现这一点。否则,使用单选按钮。

标签: c# asp.net-mvc razor checkbox


【解决方案1】:

您可以简单地使用“CheckBoxFor”Html 帮助程序并绑定到每个属性。然后,当您发布时,您可以在模型上调用 TryUpdateModel()。

@using (Html.BeginForm())
{
    @HtmlHiddenFor(m => m.Id)
    <div>First - @Html.CheckBoxFor(m => m.First)</div>
    <div>Second - @Html.CheckBoxFor(m => m.Second)</div>
    <div>Third - @Html.CheckBoxFor(m => m.Third)</div>
    <input type="submit">
}

[HttpPost]
public ActionResult SomeActionMethod(int id)
{
    var model = new MyClass(); // build your model however you like
    TryUpdateModel(model);
}

【讨论】:

    【解决方案2】:

    如果我正确理解您的问题,您只希望选择其中一项(第一、第二或第三)。对于此行为,请使用单选按钮。复选框允许选择每个项目,无论是否选择了其他项目。单选按钮一次只允许选择一项。

    【讨论】:

    • 哦,你说得对,我需要单选按钮!但无论如何我也不知道如何使用它们,现在去谷歌搜索。
    【解决方案3】:

    只是为了回答您关于复选框的问题:

    @Html.LabelFor(m => m.First, "First -") @Html.CheckBoxFor(m => m.First)
    @Html.LabelFor(m => m.First, "Second -") @Html.CheckBoxFor(m => m.Second)
    @Html.LabelFor(m => m.First, "Third -") @Html.CheckBoxFor(m => m.Third)
    

    包装文本和复选框,允许用户单击标签并选择/取消选择复选框。或者,不要用标签包装复选框和文本,只需使用LabelFor

    现在...要实现用户只检查其中一项,请为此使用 RadioButtons。

    在此处查看更详细的答案:https://stackoverflow.com/a/5621200/7720

    【讨论】:

      【解决方案4】:

      使用 RadioButtonFor。您的模型中只需要一个属性。

      型号:

      public byte MyOption { get; set; }
      

      查看:

      @Html.RadioButtonFor(m => model.MyOption, 1) 1
      @Html.RadioButtonFor(m => model.MyOption, 2) 2
      @Html.RadioButtonFor(m => model.MyOption, 3) 3
      

      【讨论】:

        猜你喜欢
        • 2013-05-15
        • 2010-12-20
        • 1970-01-01
        • 2013-05-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-05
        • 1970-01-01
        相关资源
        最近更新 更多