I have an action that takes a list of models. I'd like to validate each one individually vs. the entire model collection at once. I'm trying to use TryValidateModel, but it appears that if any one of my models is invalid, all of them are invalid. My form displays 5 SurveyResponseModels (a class with two Required strings and two ints). If I fill out all five models completely, I get validCount = 5 below. However, if any of the five models are incomplete (thus failing validation), I get a validCount of 0. Is the expected behavior of TryValidateModel? If so, any ideas on how I can validate these one at a time?
[HttpPost]
public ActionResult Create(IList<SurveyResponseModel> respondents)
{
int validCount = 0;
foreach (SurveyResponseModel respondent in respondents)
{
if (TryValidateModel(respondent))
{
validCount++;
}
}
ModelState.AddModelError("", validCount.ToString() + " respondents passed validation");
}
Looking at the code, it appears to me that TryValidateModel
will validate all models of the type given by the object provided, not just that particular object itself. Moreover, it returns the current value of the ModelState.IsValid
property so that once there is an invalid model, all invocations of TryValidateModel
will return false. If you want to do something like this, I think that you'll need to get and run the validators for each model instance yourself on that particular model instance.
I also think that the model validators have already been run by the time you are invoking them manually. You can check this (for an invalid model) by looking at the value of ModelState.IsValid
before your loop. If it's false, then it means that the validators were run by the model binder, which is what I think happens.
You can find the source code for MVC at http://aspnet.codeplex.com/.
TryValidateModel()
adds to the list of validation errors. Use ModelState.Clear()
to remove previous errors. Validation occurs as part of the model binding process, automatically, unless the [ValidateInput(false)]
attribute is used. See https://stackoverflow.com/a/8581918/1238406 for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With