0

我有这样的事情:

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]

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

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

4

4 回答 4

2

If I understand your question correctly, you only want one of the items (First, Second or Third) to be selected. For this behavior use a radiobutton. Checkboxes allow each item to be selected regardless if the other item is selected. A radiobutton will only allow one of the items to be selected at a time.

于 2012-12-26T18:47:42.027 回答
2

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

@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

于 2012-12-26T18:48:24.820 回答
1

使用 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
于 2012-12-26T19:20:09.640 回答
1

You can simply use the "CheckBoxFor" Html helper and bind to each property. Then, when you post, you can call TryUpdateModel() on your model.

@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);
}
于 2012-12-26T18:44:01.380 回答