如何仅使用 DataAnnotations 验证 Viewmodel 中的部分字段?

发布于 2024-10-06 00:08:51 字数 693 浏览 0 评论 0原文

我有一个如下所示的 Viewmodel:

public class Viewmodel
{

  public int Type {get;set} // 0 if typeA, 1 if typeB

  [Required]
  public string AProperty1 {get;set}

  [Required]
  public string AProperty1 {get;set}

  ...

  [Required]
  public string BProperty1 {get;set}

  [Required]
  public string BProperty1 {get;set}
}

有 2 个表单获取此 viewmodel,在 FormA 中用户输入 AProperty1、AProperty2 等,BProperty-s 返回为 null。 与FormB 相同。 表单的类型(FormA 或 FormB)被分配给 ViewModel.type 字段。

所以问题是,在我的控制器中,我检查 ModelState.IsValid 属性,它在两种情况下都会为 false,因为一半的字段始终为空。

一种可能的解决方案是以某种方式覆盖 ModelView 中的 ModelState.IsValid 属性,以便我可以将类型传递给它。但据我所知没有办法。

还有其他解决方案吗? (它最好应该能够与客户端验证一起使用)

I've got a Viewmodel that looks like this:

public class Viewmodel
{

  public int Type {get;set} // 0 if typeA, 1 if typeB

  [Required]
  public string AProperty1 {get;set}

  [Required]
  public string AProperty1 {get;set}

  ...

  [Required]
  public string BProperty1 {get;set}

  [Required]
  public string BProperty1 {get;set}
}

There are 2 forms that get this viewmodel and in FormA user inputs AProperty1, AProperty2 etc. and BProperty-s return as null.
The same with FormB.
The type of form (FormA or FormB) is assigned to the ViewModel.type field.

So the problem is that in my controller I check the ModelState.IsValid property and it'll be false in both ways because half of the fields are always null.

One possible solution could be to somehow override ModelState.IsValid property in my ModelView so that I could pass the type to it. But as far as i know there is no way to.

Are there any other solutions? (it preferrably should be able to use with client-side validation)

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

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

发布评论

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

评论(1

骄兵必败 2024-10-13 00:08:51

如果确实需要为两个不同的视图仅使用一个 ViewModel,那么“部分验证”可能是您的解决方案。查看此博客:

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

If it is really a requirement to have only one ViewModel for two different views, "Partial Validation" could be your solution. Check out this blog:

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

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