In MVC, should the View know the Model?

≡放荡痞女 提交于 2019-12-21 17:35:25

问题


Should the view know the model:

or not:

?


回答1:


Programmers often shortcut this and make the view specific to the model. For instance, if you're in a CRM app the model might have a firstName field; the view then assumes the model object it's given has a firstName field and shows that in the appropriate place.

This of course isn't reusable. If you are making a View to display a table of data, it shouldn't care which model field is shown in which column. It should just handle displaying and formatting tabular data in a generic way. But if your view is of a web page that's custom-built to the specific data it's showing, it can be okay.

So you have to decide on a case-by-case basis whether you want a view to know about the specific data it's showing or if you want it to be a reusable component.

In either way, any changes to the model's data should always happen through the controller. The controller is responsible for enforcing your business logic, and that's impossible when something else is circumventing it.




回答2:


No, the model and view communicate through the controller.

I mean, you can have them know each other, but that would induce tight coupling and would be hard to extend the functionality of the application.




回答3:


By rights, Model, the underlying business entity, shouldn't be exposed directly to View. We normally use ViewModel, a presentation-specific model, which is derived from one or more Models.



来源:https://stackoverflow.com/questions/27950039/in-mvc-should-the-view-know-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!