它是用ModelState.Remove处理的ModelState正确的方法? [英] Is it correct way to use ModelState.Remove to deal with ModelState?

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

问题描述

进出口工作在一个大MVC3 Web应用程序,并有关于 ModelState.IsValid 方法的烦恼。

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

ModelState中在几乎所有我的控制器被使用,以便验证张贴的数据。
的意见都是基于其包含不同类和这些类含有一些可能被标记为属性的ViewModels [必需]

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

我遇到的问题是所要求的性能有时不是必需的,不必使用 ModelState.Remove 方法IM让 ModelState.IsValid 为真。

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.

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

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

推荐答案

如果你使用了 [必需] 属性相同的视图模型有两种不同的情况下,之一,需要的属性和一个地方没有,那么你就需要手动修改的ModelState 为你做。

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天全站免登陆