使用 ModelState.Remove 处理 ModelState 是否正确? [英] Is it correct way to use ModelState.Remove to deal with ModelState?

查看:35
本文介绍了使用 ModelState.Remove 处理 ModelState 是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个大型 MVC3 Web 应用程序,并且对 ModelState.IsValid 方法感到烦恼.

ModelState 几乎在我所有的控制器中都被使用,以便验证发布的数据.这些视图都基于包含不同类的 ViewModel,这些类显然包含可以标记为 [Required] 的属性.

我遇到的问题是有时不需要所需的属性,我必须使用 ModelState.Remove 方法,以便 ModelState.IsValid 变为 true.

我的问题是使用 ModelState.Remove,这是正确的做事方式还是有更有效的方法.

解决方案

如果您在两个不同的上下文中使用带有 [Required] 属性的相同视图模型,其中一个是需要该属性的如果不是,则需要在执行时手动更改 ModelState.

另一种方法是使用不同的视图模型.也许有一个包含所有属性的基类,除了所讨论的必需属性.然后从中派生出两个视图模型,一个具有需要的属性,另一个具有不需要的属性(我知道这是重复的).您可以决定将它们完全分开,而不使用继承.

Im working on a big MVC3 web application and have an annoyance regarding the ModelState.IsValid method.

ModelState is being used in nearly all of my controllers so to validate the data being posted. The views are all based on ViewModels which contain different classes and these classes obviously contain properties which could be marked as [Required].

The problem i am having is the required properties are sometimes not required and im having to use the ModelState.Remove method so that ModelState.IsValid becomes true.

My question is by using ModelState.Remove, is this the correct way of doing things or is there a more efficient approach.

解决方案

If you're using the same view model with a [Required] property in two different contexts, one where the property is required and one where it isn't, then you'll need to manually alter the ModelState as you're doing.

An alternative is to use a different view model. Perhaps have a base class with all properties except the required property in question. Then derive two view models from it, one with the property where is it required and one with the property where it is not (it's duplication, I know). You may decide to keep them entirely separate altogether and not use inheritance.

这篇关于使用 ModelState.Remove 处理 ModelState 是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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