我正在尝试使用ModelState验证表单,但我的ModelState始终显示为有效。例如:当我尝试保存每个具有相同SSN的2 Person 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; }
}
答案 0 :(得分:0)
我写了一个测试来验证你的验证,看起来很不错。
[Test]
public void Should_validate_person_form_model()
{
var input = new PersonsFormModel();
input.Add(new PersonFormModel { SSN = "33" });
input.Add(new PersonFormModel { SSN = "33" });
_controller.ViewData.ModelState.Clear();
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(input,
new ValidationContext(input, null, null),
results,true);
Assert.IsTrue(!isValid, "Cannot have duplicates.");
}
因此要么没有被调用,要么你的数据有效。
要测试前者,您可以在Validate中设置一个断点,并确认它正在被击中。
要测试后者,您可以提供发布的确切数据和所涉及的完整模型。
答案 1 :(得分:0)
这是我解决我遇到的问题的方法:
***Controller:***
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 });
}
***Model:***
public class PersonsFormModel : IValidatableObject
{
public PersonsFormModel()
{
this.Instance = new List<PersonFormModel>();
}
public List<PrequalifyOccupantListPersonFormModel> Instance { get; set; }
public void Add(PersonFormModel personFormModel)
{
Instance.Add(personFormModel);
}
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 Instance.Select(element => element.SSN);
}
}
}
public class PersonFormModel
{
[Required(ErrorMessage = "SSN is required")]
public string SSN { get; set; }
}
View:
// Note, I am passing the "Instance" here.
var postData = JSON.stringify({ Instance: list });
RealPage.DataManager.POST({
url: "/Approval/SaveOccupantsDetailedInformation"
, data: postData
, success: function (data) {
if (data && data.Success) {
}
}
});