如何防止在 mvc 中多次选择 Razor 控件单选按钮?

How to prevent multiple selection of Razor control radio button in mvc?

我有男性和女性选项的单选按钮,但问题是他们都被选中了,而不是任何一个。

我的控制器:

 private List<SelectedGenderModel> GetGender()
        {
            var gender = new List<SelectedGenderModel>();
            gender.Add(new SelectedGenderModel { Name = "Male", Id = 1, Selected = false });
            gender.Add(new SelectedGenderModel { Name = "Female", Id = 2, Selected = false });
            return gender;
        }

我的看法:

@model MvcDemo.Models.EmployeeModel
 @for (int i = 0; i < Model.Gender.Count; i++)
                {
                    @Html.RadioButtonFor(m => m.Gender[i].Selected, new { id = "gender_" + i, name = "gendernm_" })
                    @Html.HiddenFor(m => m.Gender[i].Id)
                    @Html.HiddenFor(m => m.Gender[i].Name)
                    @Html.DisplayFor(m => m.Gender[i].Name)
                }

我的视图模型:

public class EmployeeModel
    {
            public int Id { get; set; }
            public string Fullname { get; set; }
            public List<SelectedGenderModel> Gender { get; set; }
    }

我的数据模型:

public partial class EmployeeMaster
    {
        public int Id { get; set; }
        public string Fullname { get; set; }
        public Nullable<bool> Gender { get; set; }
    }

那么如何防止单选按钮的多选?

您的循环正在呈现 2 个具有不同名称(name="Gender[0].Selected"name="Gender[1].Selected")的单选按钮,这意味着它们属于 2 个不同的组。您可能认为 new { name = "gendernm_" } 正在修改 name 属性,但幸运的是它不是(否则模型绑定将在 post 返回时失败)。

不清楚为什么你的数据模型有 属性 bool? Gendertrue 的值应该表示男性还是女性?null 值是什么意思? 也许 bool IsMalebool IsFemale 对其他人来说更有意义,但为什么不直接将其设为字符串(或枚举)呢?

将您的视图模型更改为

public class EmployeeModel
{
  public int Id { get; set; }
  public string Fullname { get; set; }
  [Required]
  public string Gender { get; set; }
}

并在视图中

@Html.RadioButtonFor(m => m.Gender, "Male", new { id = "Male" })
<label for"Male">Male</label>
@Html.RadioButtonFor(m => m.Gender, "Female", new { id = "Female" })
<label for"Female">Female</label>
@Html.ValidationMessageFor(m => m.Gender)

如果你想让它成为可空的 bool,那么你可以使用

@Html.RadioButtonFor(m => m.Gender, "True", new { id = "Male" })
<label for"Male">Male</label>
@Html.RadioButtonFor(m => m.Gender, "False", new { id = "Female" })
<label for"Female">Female</label>
@Html.RadioButtonFor(m => m.Gender, "", new { id = "Unknown" })
<label for"Unknown">Not sure</label>