ASP.NET MVC 视图模型模式 - 验证和数据库操作
在开发之初,我面临着“域模型和视图之间的阻抗不匹配”的问题。为了解决这个问题,我决定使用 ViewModel 模式 - 对于每个视图(强类型),我们创建 viewmodel 类。但是验证逻辑位于哪里 - 在视图模型类中还是在我们的域模型对象中?我们需要在哪里执行查询数据库的操作 - 在控制器操作中,然后填充视图模型或直接在视图模型中?
谢谢。
At the start of the development I faced with problem called "an impedance mismatch between domain model and the view". To solve this problem I decide to use ViewModel pattern - for every view (that is strongly typed) we create viewmodel class. But where is the validation logic is locate - in viewmodel classes or in our domain model objects? And where we need to perform operations to query database - in controller action, and then populate viewmodel or straight in viewmodel?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该具有视图模型的验证逻辑。这是视图发送的内容以及应该验证的内容。就填充视图模型而言,以下是如何进行:编写一个查询数据库并返回模型的存储库。然后将这些模型映射到视图模型(AutoMapper 可以在这里为您提供帮助)。最后将视图模型返回给视图。这也以相反的方式工作:用户将一些数据以视图模型的形式发布到控制器操作,一旦验证,该数据就会映射回模型并传递到存储库进行更新。
作为数据注释的替代方案,您可以查看 FluentValidation 来验证您的视图模型。它集成得很好< /a> 与 ASP.NET MVC。
You should have validation logic for the viewmodel. This is what the view sends and what should be validated. As far as populating the viewmodel is concerned here's how to proceed: write a repository which queries the database and returns models. Then map those models to viewmodels (AutoMapper can help you here). Finally return viewmodels to the view. This also works the other way around: the users POSTs some data to a controller action as the form of a viewmodel which once validated is mapped back to a model and passed to the repository for update.
As an alternative to Data Annotations you may take a look at FluentValidation for validating your view models. It integrates nicely with ASP.NET MVC.