本文介绍了ASP.NET MVC3 TryValidateModel验证整个模型集合,而不只是单一实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有需要的型号列表的操作。我想单独验证每一个对整个模型收集一次。我试图用TryValidateModel,但现在看来,如果我的任何一款车型是无效的,个个都是无效的。我的表单显示5 SurveyResponseModels(有两个必需的字符串和两个整数的一类)。如果我完全填写所有五款车型,我得到以下validCount = 5。但是,如果任何的五款车型都是不完整的(因此验证失败),我得到一个0 validCount是TryValidateModel的预期行为?如果是这样,我如何能在一个时间验证这些之一的任何想法?

  [HttpPost]
    公众的ActionResult创建(IList的< SurveyResponseModel>受访者)
    {
        INT validCount = 0;        的foreach(在受访者SurveyResponseModel答辩)
        {
            如果(TryValidateModel(答辩))
            {
                validCount ++;
            }
        }
        ModelState.AddModelError(,validCount.ToString()+的受访者通过验证);
    }


解决方案

TryValidateModel()添加到验证错误的列表。使用 ModelState.Clear()删除previous错误。出现验证作为模型的一部分​​结合过程中,自动,除非 [ValidateInput(假)]用于属性。请参见了解更多信息。

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");
    }
解决方案

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 http://stackoverflow.com/a/8581918/1238406 for more info.

这篇关于ASP.NET MVC3 TryValidateModel验证整个模型集合,而不只是单一实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:20