基于单选按钮选择的多个验证?

时间:2015-03-04 14:28:12

标签: jquery asp.net-mvc validation

我目前正在尝试验证MVC视图中的文本字段以符合多个条件。

  • 总的来说,该字段不能为空。
  • 将会有一个单选按钮组,其中包含选项AB。如果选择了A,我将需要确保输入的内容是我正在比较的数据集中的有效条目。如果选择B,则无需执行此验证。

我已经进行了验证,以防止文本字段为空,以及验证输入的内容与数据集中的内容。我正在尝试添加RadioButtons。

目前,我正在使用DataAnnotations验证我的表单。目前,我总是使用远程验证器验证文本字段。继承我的观点模型。

[Required(ErrorMessage = "{0} is required")]
[Remote ("ControllerMethod", "Controller", ErrorMessage = "{0} is not a in the data set.")]
[Display(Name = "Account")] 
public string Account { get; set; }

我不确定如何做的是根据RadioButton中选择的内容添加另一级别的验证。

1 个答案:

答案 0 :(得分:1)

您可以使用AdditionalFields属性的[Remote]属性,将所选单选按钮的值传递给控制器​​。假设您的绑定属性的名称,单选按钮名为Option,然后

[Required(ErrorMessage = "{0} is required")]
[Remote ("ControllerMethod", "Controller", AdditionalFields = "Option", ErrorMessage = "{0} is not a in the data set.")]
[Display(Name = "Account")] 
public string Account { get; set; }

并修改控制器方法以接受AccountOption

的值
public ActionResult ControllerMethod(string account, string option)
{
  if (option == "B")
  {
    return true; // ignore it and indicate success
  }
  else
  {
    // call service to validate and return result
  }
}
相关问题