我正在尝试使用ModelState验证表单,但我的ModelState始终显示为有效。例如:当我尝试保存一个包含相同社会保障号码的2个人的formModel时,ModelState返回有效。我正在使用IValidatableObject来验证我的formmodel。有什么想法我可能做错了什么?我正在使用带有MVC 3的.Net 4.0。
public JsonResult LoadOccupantsDetailedInformation()
{
//Load the personsFormModel with data
return new JsonpResult(personsFormModel, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult SaveOccupantsDetailedInformation(
PersonsFormModel personsFormModel)
{
//This line is always returning true even if I pass 2 persons with the same ssn
if (ModelState.IsValid == false)
{
var errorList = ModelState.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
);
return Json(new { Errors = errorList });
}
//Save the data in personsFormModel to database
return Json(new JsonResultViewModel { Success = true });
}
public partial class PersonsFormModel : List<PersonFormModel>, IValidatableObject
{
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(
ValidationContext validationContext)
{
var validationResults
= new List<System.ComponentModel.DataAnnotations.ValidationResult>();
if (this.SSNs.Count() > this.SSNs.Distinct().Count())
{
validationResults.Add(new System.ComponentModel.DataAnnotations.ValidationResult(
"All the persons in the household should have a unique SSN\\ITIN number",
new[] { "SSN" }));
}
return validationResults;
}
private IEnumerable<string> SSNs
{
get
{
return this.Select(element => element.SSN);
}
}
}
public class PrequalifyOccupantListPersonDetailedFormModel
{
[Required(ErrorMessage = "SSN is required")]
public string SSN { get; set; }
}