Radiobutton就像一个复选框MVC

时间:2016-06-14 06:02:59

标签: c# asp.net-mvc

使用下面的代码,我可以同时选择多个单选按钮,这是一个问题,一个真正的单选按钮只适用于一个选定的项目。我如何重新安排我的代码,使其像一个真正的单选按钮,而不像下面的代码复选框?

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>
}

其余代码:

型号:

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"}
        };
    }
}

控制器:

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!";
}

总结:这段代码让你选择了多个单选按钮,我不想这样,我只希望从众多选项中选择一种。

1 个答案:

答案 0 :(得分:1)

每个单选按钮都有不同的name属性,因此不会对其进行分组。您的模型需要一个属性来绑定选定的值,以及选项的项集合

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

和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);

并在视图中

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)