在ASP.NET MVC验证的机型列表编程 [英] Validate list of models programmatically in ASP.NET MVC

查看:143
本文介绍了在ASP.NET MVC验证的机型列表编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个编程方式来验证模型的一个列表。

I would like to validate list of models one by one programmatically.

我试过 TryValidateModel 但看起来像它聚合验证错误,这样,当我走过的10个型号列表循环,如果第五模式是无效的,因为模型6-10 TryValidateModel回报

I tried TryValidateModel but looks like it aggregates validation errors, so that when I iterate through the list of 10 models, if 5th model is not valid, for models 6-10 TryValidateModel returns false.

推荐答案

您可以使用控制器方法 ValidateModel TryValidateModel

You can use controller methods ValidateModel or TryValidateModel.

ValidateModel - 如果模式是无效抛出异常

ValidateModel - throws exception if model is not valid.

TryValidateModel - 布尔返回这表明,如果模型是有效的。

TryValidateModel - returns bool which indicates if model is valid.

从<一个href=\"https://msdn.microsoft.com/en-US/library/system.web.mvc.controller.tryvalidatemodel%28v=vs.118%29.aspx\"相对=nofollow> MSDN :

在正在验证的模式,为所有属性都验证程序是
  如果至少有一个表单输入绑定到一个模型属性运行。该
  TryValidateModel就像是除了ValidateModel方法
  TryValidateModel方法不抛出
  InvalidOperationExceptionexception如果模型验证失败。

When a model is being validated, all validators for all properties are run if at least one form input is bound to a model property. The TryValidateModel is like the ValidateModel method except that the TryValidateModel method does not throw an InvalidOperationExceptionexception if the model validation fails.

如果您验证的的型号列表的一个接一个,你可能想通过调用重置的ModelState每次迭代 ModelState.Clear()

If you validate list of models one by one, you probably would like to reset ModelState for each iteration by calling ModelState.Clear().

这篇关于在ASP.NET MVC验证的机型列表编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆