是否可以手动更新ModelState.IsValid? [英] Is it possible to update ModelState.IsValid manually?

查看:103
本文介绍了是否可以手动更新ModelState.IsValid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用内置的验证功能尽可能。我也想用同样的模式CRUD方法。

I would like to use the built-in validation features as far as possible. I would also like to use the same model for CRUD methods.

但是,作为一个下拉列表中无法使用标准模式来完成,我必须手动验证。在后背法,我想只是验证下拉列表,这个结果添加到ModelState中,这样我就不必验证所有与数据注解来实现其他参数。是否有可能实现这一目标?

However, as a drop down list cannot be done using the standard pattern, I have to validate it manually. In the post back method, I would like to just validate the drop down list and add this result to ModelState so that I don't have to validate all the other parameters which are done with Data Annotation. Is it possible to achieve this?

我可能是弄错了下拉列表中,但是从我读,一个下拉列表中HTML对象的名称不能相同,在模型中的属性,以便正确设置选择的值。难道还要用数据诠释这个解决方法吗?

I may be mistaken about the drop down list, but from what I read, the Html object name for a drop down list cannot be the same as the property in the Model in order for the selected value to be set correctly. Is it still possible to use Data Annotation with this workaround?

感谢。

推荐答案

您可以使用<$c$c>addModelError

ModelState.AddModelError(key,message)

当您使用,它将无效的ModelState让的isValid 将返回false。

when you use that, it will invalidate the ModelState so isValid will return false.

更新结果
看到改为@彼得的回答后评论

如果您想从影响的isValid()结果排除元素,你可以使用<$c$c>ModelState.Remove(field)之前调用方法的isValid()

If you want to exclude an element from affecting the isValid() result, you can use the ModelState.Remove(field) method before calling isValid().

这篇关于是否可以手动更新ModelState.IsValid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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