ASP.NET MVC、Model 和 ViewModel 关注点分离? [英] ASP.NET MVC, Model and ViewModel separation of concerns?

查看:28
本文介绍了ASP.NET MVC、Model 和 ViewModel 关注点分离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我一直在探索当底层模型很复杂时,组织 ASP.NET MVC 应用程序的表示层的最佳方法是什么.到现在为止出现的是带有 ViewModel 对象的 MVVM 架构.但是,我不确定这种架构在万一情况下的最佳实践是什么.

Lately, I've been exploring what's the best way to organize presentation layer of ASP.NET MVC application when underlying Model is complex. What came up till now is MVVM architecture with their ViewModel objects. However, I'm not sure what are the best practices when this kind of architecture is in case.

  • ViewModel 对象可以包含 Model 对象吗?
  • 如果使用 MVVM,是否建议在视图上使用模型对象?
  • 应该在何处实现验证,在 ViewModel 还是 Model 类上?
  • 业务层(服务层)是否应该知道 ViewModel ,谁负责 ViewModel 和 Model 之间的映射?

推荐答案

  • 大多数情况下,当我们需要发送多种类型的模型对象时,或者当我们需要传递仅在视图中需要的更多属性时,ModelView 对象只是保存模型对象的容器.
  • 如果 View 的工作是显示 Model 的详细信息,而没有其他东西可以传递给 View,为什么不呢?
  • 视情况而定.您可以使用 ModelView 和 Model 类来在层之间传输数据.并通过自定义模型绑定器或服务层进行验证.
  • 他们没有理由不知道 ModelViews.但通常你只是从控制器的服务层获取请求的模型,然后将它/它们直接或在 ModelView 中传递给视图.
  • 顺便说一句,我不会将 ModelViews 视为一种架构.这更像是当你需要一个时使用一个".毕竟,这样做传递数据给视图是没有意义的:

    BTW, I wouldn't consider ModelViews as an architecture. It's more like "use one when you need one". After all, there's no point in doing this to pass data to view :

    class SomeModelView {
        public MyModel model { get; set; }
    }
    

    只要传递 MyModel 就足以让视图完成它的工作.

    Just pass the MyModel if that's enough for the view to do its job.

    这篇关于ASP.NET MVC、Model 和 ViewModel 关注点分离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆