简体   繁体   English

单选按钮的作用类似于复选框MVC

[英]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. 简介:此代码让您选择多个单选按钮,我不希望那样,我希望在许多选项中仅选择一个。

Each radio button has a different name attribute so they are not grouped. 每个单选按钮都有一个不同的name属性,因此未分组。 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 并在GET方法中

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM