user6096770
user6096770

Reputation:

Radiobutton acting like a checkbox MVC

With the code below, i can select multiple radio buttons at the same time, that is a problem, a true radio button only works with ONE selected item. How do i re-arrange my code so that it acts like a real radio button and not like a checkbox like the code below?

for (int i = 0; i < Model.RadioButtonItems.Count; i++)
{
    <div>
        @Html.HiddenFor(m => m.RadioButtonItems[i].RBName)
        @Html.LabelFor(l => l.RadioButtonItems[i].RBIsSelected, Model.RadioButtonItems[i].RBName)
        @Html.RadioButtonFor(r => r.RadioButtonItems[i].RBIsSelected, true);
    </div>
}

The rest of code:

Model:

public class ModelVariables
{
    public List<Item> RadioButtonItems { get; set; }
}

public class Item
{
    public string RBName { get; set; }
    public bool RBIsSelected { get; set; }
}

public static class Repository
{
    public static List<Item> RBFetchItems()
    {
        return new List<Item>()
        {
            new Item() {RBName = "Metal"},
            new Item() {RBName = "Jazz"},
            new Item() {RBName = "Trance"}
        };
    }
}

Controller:

var selectedRBItems = model.RadioButtonItems.Where(x => x.RBIsSelected).Select(x => x.RBName).ToList();
if (model.RadioButtonItems != null && selectedRBItems.Count > 0)
{
    ViewBag.RBResults = "Successfully Logged Pressed RB's!";
}
else
{
    ViewBag.RBResults = "You must select a radio button!";
}

Summary: this code let's you select multiple radiobuttons, i DONT want that, i want only one possible selection out of many options.

Upvotes: 0

Views: 421

Answers (1)

user3559349
user3559349

Reputation:

Each radio button has a different name attribute so they are not grouped. Your model needs a property to bind the selected value to, and a collection of items for the options

public class ModelVariables
{
    [Required(ErrorMessage = "...")]
    public string SelectedValue { get; set; }
    public List<string> Options { get; set; }
}

and in the GET method

var model = new ModelVariables()
{
    Options = new List<string>() { "Metal", "Jazz", "Trance" },
    SelectedValue = ? // set this if you want one of the buttons initially selected
};
return View(model);

and in the view

foreach (var option in Model.Options)
{
    <label>
        @Html.RadionButtonFor(m => m.SelectedValue, option, new { id = "" })
        <span>@option</span>
    </label>
}
// add the following if you do not set an initial value in the GET method
@Html.ValidationMessageFor(m => m.SelectedValue)

Upvotes: 1

Related Questions