Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3 TryValidateModel validates entire model collection, not just single instance

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");
    }
like image 980
Andrew Avatar asked Dec 28 '22 02:12

Andrew


2 Answers

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/.

like image 112
tvanfosson Avatar answered Jan 17 '23 14:01

tvanfosson


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.

like image 32
Barumpus Avatar answered Jan 17 '23 15:01

Barumpus