要解决ASP.net MVC中单选按钮验证不起作用的问题,可以按照以下步骤进行操作:
[Required]
特性确保必须选择一个选项。public class UserModel
{
[Required(ErrorMessage = "请选择性别")]
public string Gender { get; set; }
}
@Html.RadioButtonFor
方法生成单选按钮,并使用@Html.ValidationMessageFor
方法显示验证错误消息。@model UserModel
@using (Html.BeginForm())
{
@Html.RadioButtonFor(model => model.Gender, "Male") 女
@Html.RadioButtonFor(model => model.Gender, "Female") 男
@Html.ValidationMessageFor(model => model.Gender)
}
ModelState.IsValid
属性检查验证结果。如果验证失败,返回视图以显示错误消息。[HttpPost]
public ActionResult Register(UserModel model)
{
if (ModelState.IsValid)
{
// 验证成功,执行其他操作
return RedirectToAction("Success");
}
// 验证失败,返回视图以显示错误消息
return View(model);
}
通过以上步骤,单选按钮的验证应该能够正常起作用。如果用户未选择任何选项,将会显示错误消息。