使用 ASP.NET MVC 验证模型的部分内容数据注释

发布于 2024-10-04 08:41:03 字数 396 浏览 0 评论 0原文

我们使用数据注释设置 POCO 类。

对于这些类之一,我们涉及多个视图,以便用户填充他们的所有数据。例如,如果它是一个以用户名和密码作为属性的类,我们将在第一页上让用户指定他们的用户名,并在第二页上指定他们的密码。

现在,如果我使用完整的 POCO 类(需要提供用户名和密码),那么当我们询问 ModelState.IsValid 时,由于尚未提供密码,因此会得到 false,但我们知道密码将会在下一页提供!

是否有一种通用方法可以让我们验证应该为其提供值的模型元素而不是整个模型?我知道我可以从 ModelState 中删除单个项目的错误。

我知道我们可以分离出模型元素,以便为正在执行的条目的每个页面部分拥有单独的模型,但这感觉就像我们正在更改底层类以更适合视图。

问候

杰米

We have our POCO classes setup using Data Annotations.

For one of these classes, we invole more than one view for the user to populate all of their data. For example if it were a class with username and password as properties we would on the first page get the user to specify their username and on the second page specify their password.

Now, if i use the full POCO class (which requires that both username & password are supplied) then when we ask ModelState.IsValid were get false since the password hasn't yet been supplied, but we know that the password is going to be supplied on the next page!

Is there a generic way for us to validate those elements of the model for which values should have been provided rather than the whole Model? I know that i can remove the errors for individual items from the ModelState.

I know that we could separate out the model elements to have separate models for each page part of the entry that is being performed but this feels like we are changing the underlying class to fit more with the view.

Regards

Jamie

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

在你怀里撒娇 2024-10-11 08:41:04

我相信史蒂夫在这里的方法可以解决这个问题

http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/

实质上,他过滤掉了那些没有传入值的键。

I believe the approach here by Steve deals with this

http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/

in essence he filters out those keys for which there are no incoming values.

小…楫夜泊 2024-10-11 08:41:04

尝试将验证放在 ViewModel 类上。每个视图都有自己的 ViewModel 类。一个带有用户名,另一个带有密码。在收集到所需的所有数据之前,请勿使用该模型。

Try putting the validation on the ViewModel classes. Each view will have its own ViewModel class. One with the username, the other with the password. Don't use the model until you gathered all the data you need.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文