当绑定的编辑模型!=视图模型时如何处理模型验证

发布于 2024-11-01 06:25:53 字数 121 浏览 2 评论 0原文

我在 ASP.NET MVC 2 中遇到一种情况,其中有一个表单,其字段基于视图模型提供的信息,但其发布的数据是由更精简的编辑模型表示的数据的子集。我想向编辑模型添加简单的数据注释验证,但由于视图基于视图模型,我不确定如何继续。

I have a situation in ASP.NET MVC 2 where I have a form whose fields are based on info supplied by a view model, but whose posted data is a subset of that data represented by a slimmer edit model. I'd like to add simple data annotation validation to the edit model, but since the view is based on the view model, I'm not sure how to proceed.

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

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

发布评论

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

评论(1

手长情犹 2024-11-08 06:25:53

视图模型和控制器操作参数不必相同。

在您的情况下,这意味着您可能正在使用更丰富的模型类来生成视图(甚至可能发布比需要的更多信息),但您的控制器操作只会使用发布的数据中的一些信息来填充更简单的应用程序模型对象实例。没问题。只要字段命名就足以正确填充属性。

您可能有这两个类:

public class User
{
    [Required]
    public string Username { get; set; }

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

public class Person: User
{
    public string Name { get; set; }

    public string Address { get; set; }
}

然后您的视图将使用 Person 并且您的控制器操作将具有 User 类型的参数。美好的。它会起作用的。

这些类也不需要相互继承。我刚刚在这个简单的示例中做到了这一点,因为这样它们就共享公共属性名称。但除此之外,只要发布的字段名称能够对绑定到控制器操作参数类属性进行建模,它们就不必以任何方式关联。

View model and controller action parameters don't have to be the same.

In your case this means that you may be using a richer model class to generate your view (and maybe even posting more information than needed) but your controller action would only use some information from that posted data to populate a simpler application model object instance. No problem. As long as field naming will suffice to populate properties correctly.

You may have these two classes:

public class User
{
    [Required]
    public string Username { get; set; }

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

public class Person: User
{
    public string Name { get; set; }

    public string Address { get; set; }
}

and then your view would be using Person and your controller action would have a parameter of type User. Fine. It will work.

There's no need for these classes to inherit each other either. I've just made it so in this simple example because this way they both share common property names. But otherwise they don't have to be related in any way shape or form as long as posted field names will be able to model bind to controller action parameter class properties.

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