0

I have something like this:

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

Now, i want to generate something, that will display this:

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

And i want those checkboxes to select only one item from those properties, how can i do it?

Edit: Sorry guys, i don't really need checkboxes, what i need is radiobuttons for that. If someone has any example code that shows how to solve my problem using radiobuttons, i would be grateful.

ojek
  • 9,680
  • 21
  • 71
  • 110
  • Mutually exclusive checkboxes are not standard in any HTML framework. You should use javascript for achieving that. Otherwise, use radiobuttons. – Adrian Salazar Dec 26 '12 at 18:50

4 Answers4

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.

Chuck Conway
  • 16,287
  • 11
  • 58
  • 101
  • Oh, you are right, i need radiobuttons! But anyways i don't know how to use them either, gonna google that now. – ojek Dec 26 '12 at 18:51
2

Just to answer your question about checkboxes:

@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)

Wrapping the text and the checkbox, allow the user to click in the label and select/deselect the check box. Or, instead of wrapping the checkbox and text with a label, just use LabelFor.

Now... to accomplish that the user should check only one of those, please use a RadioButtons for that.

See the more detailed answer here: https://stackoverflow.com/a/5621200/7720

Community
  • 1
  • 1
Romias
  • 13,783
  • 7
  • 56
  • 85
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);
}
Nick Bray
  • 1,953
  • 12
  • 18
M.Ob
  • 1,785
  • 14
  • 27
1

Use RadioButtonFor. You will need only one property in your model.

Model:

public byte MyOption { get; set; }

View:

@Html.RadioButtonFor(m => model.MyOption, 1) 1
@Html.RadioButtonFor(m => model.MyOption, 2) 2
@Html.RadioButtonFor(m => model.MyOption, 3) 3
Adriano Silva
  • 2,518
  • 1
  • 17
  • 29