In MVC, should the View know the Model?

2020-07-17 04:38发布

Should the view know the model:

enter image description here

or not:

enter image description here

?

3条回答
【Aperson】
2楼-- · 2020-07-17 04:57

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.

查看更多
劳资没心,怎么记你
3楼-- · 2020-07-17 05:11

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.

查看更多
迷人小祖宗
4楼-- · 2020-07-17 05:19

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.

查看更多
登录 后发表回答