Bind multiple radiobuttons to individual booleans

Viewed 2535

Background

I have a model containing three bools

public class PageDataModel
{
    public bool setting1 { get; set; }
    public bool setting2 { get; set; }
    public bool setting3 { get; set; }
}

If one value is true, the others must be false.

In my view, I am displaying three radio buttons:

Enter image description here

The Razor code for my view:

<div class="row">
        <div class="radio">
            @if (Model.Setting1)
            {
                @Html.RadioButtonFor(m => m.Setting1,  "Setting1", new { Checked = "checked", Name = "Group"})
            }
            else
            {
                @Html.RadioButtonFor(m => m.Setting1, "Setting1", new { Name = "Group"})
            }

            @Html.Label("Setting1")
        </div>
        <div class="radio">
            @if (Model.Setting2)
            {
                @Html.RadioButtonFor(m => m.Setting2, "Setting2", new { Checked = "checked", Name = "Group" })
            }
            else
            {
                @Html.RadioButtonFor(m => m.Setting2, "Setting2", new { Name = "Group"})
            }
            @Html.Label("Setting2")
        </div>
        <div class="radio">
            @if (Model.Setting3)
            {
                @Html.RadioButtonFor(m => m.Setting3, "Setting3", new { Checked = "checked", Name = "Group" })
            }
            else
            {
                @Html.RadioButtonFor(m => m.Setting3, "Setting3", new { Name = "Group"})
            }
            @Html.Label("Setting3")
        </div>
        <button type="submit" class="btn btn-default">Save</button>
    </div>

In my controller, I am returning a model with setting1 set to true:

var model = new PageDataModel
        {
            Setting1 = true,
            Setting2 = false,
            Setting3 = false
        };
        return View(model);

This works correctly, the page is loaded with the 'setting 1' radio button checked.

The problem

When I submit the form, the posted model contains all false values, regardless of which radio button was checked.

I've tried changing the value from "setting1" to true/false, but that had no impact on the returned data.

I'm fairly sure I'm not setting up the binding properly, but I'm not sure where I'm going wrong.

All other examples I have found are binding two radio buttons to one bool value (for example, a yes/no pair of radio buttons bound to one bool). I can change the code to use one int property, but I'd like to solve this using bools.

What am I doing wrong? Am I misusing radio buttons here?

1 Answers
Related