是否应该在使用 MVC 的每个视图中使用 ViewModel?

发布于 2024-12-03 22:45:25 字数 275 浏览 0 评论 0原文

我了解您使用 ViewModel 来存储来自其他模型和视图中使用的源的不同数据,因为模型并不总是包含您想要的内容。

我试图弄清楚为每个视图使用 ViewModel 是否合适。我问的原因是出于一致性原因。您可以有一个仅需要模型本身的视图,以及另一个必须具有 ViewModel 的视图。在您的所有视图之间混合这些好吗?或者每个 View 都应该有一个 ViewModel 吗?

了解这一点很重要,因为我的模型与数据库直接相关,因为我使用的是 Entity Framework 4.1 Code First。

I understand you use a ViewModel to store different data from other Models and sources to be used in a View, as a Model will not always hold what you want.

I'm trying to figure out if it is proper to use a ViewModel for every single View. The reason I am asking is for consistency reasons. You could have a View that only needs the Model itself and another View that has to have a ViewModel. Is it good to mix these up between all your Views? Or should every View have a ViewModel?

This is important to know since my Models are directly related to the database, as I'm using Entity Framework 4.1 Code First.

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

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

发布评论

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

评论(2

烟酒忠诚 2024-12-10 22:45:25

这不是要求,但它是最佳实践。

您希望尽可能地将数据库与演示文稿解耦,并且使用 ViewModel (即使它是相同的)可以为您提供这种分离。它还可以保持事物的一致性,这样您就不会出现一些视图带有模型而另一些视图不带有模型的情况。这种类型的设计让您思考您希望视图遵循的所有数据并找出优化方案,查看是否可能发生数据重复,将数据集中到一个位置等。

想想您的 ViewModel 就像与 View 的合同一样......这个 View 需要 X 才能工作。

前期要做的工作不多,但最终会得到回报。

It's not a requirement but it is a best practice.

You want to decouple your database from your presentation as much as possible and having a ViewModel (even if it is identical) gives you that seperation. It also keeps things consistent so you don't have some views with models and some without. This type of design makes you think about all the data you want your views to adhear to and figure out optimizations, see if duplication of data might be occurring, keep data considated to one location, etc.

Think of your ViewModel like a contract with the View.... this View requires X to work.

Little more work up front but it will pay off in the end.

长不大的小祸害 2024-12-10 22:45:25

就我个人而言,我喜欢将发送到我的视图的内容从我的模型中抽象出来。

原因是需求发生了变化,通过视图模型,我可以快速包含我需要的数据,而不会污染我的模型。

当您的模型是由框架创建时,这一点会发挥更大的作用。如果与框架相关的模型发生变化,将来抽象模型的细节可能会非常方便。

还值得记住的是,您的视图独立于控制器和模型。您可能会发现,通过利用视图模型,您可以比视图绑定到模型本身更轻松地跨控制器方法重用视图。

Personally I like to abstract what gets sent to my views away from my models.

The reason being that requirements change and with a view model I can quickly include the pieces of data I need without polluting my models.

This comes into play even more when your models are created by a framework. Abstracting away the detail of the model could be really hand in the future if your framework related models change.

It's also worth remembering that your views are independent of your controllers and models. You may find that by utilising a view model you can re-use your view across controller methods more easily than when the view is bound to the model itself.

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