当绑定的编辑模型!=视图模型时如何处理模型验证
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
视图模型和控制器操作参数不必相同。
在您的情况下,这意味着您可能正在使用更丰富的模型类来生成视图(甚至可能发布比需要的更多信息),但您的控制器操作只会使用发布的数据中的一些信息来填充更简单的应用程序模型对象实例。没问题。只要字段命名就足以正确填充属性。
您可能有这两个类:
然后您的视图将使用
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:
and then your view would be using
Person
and your controller action would have a parameter of typeUser
. 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.