在MVC中,视图应该知道模型吗? [英] In MVC, should the View know the Model?

查看:73
本文介绍了在MVC中,视图应该知道模型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

视图是否应该知道模型:

Should the view know the model:

还是不:

?

推荐答案

程序员通常会对此进行快捷操作,并使视图特定于模型.例如,如果您在CRM应用程序中,则该模型可能具有一个firstName字段.然后,该视图假定为其提供的模型对象具有一个firstName字段,并在适当的位置显示该名称.

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.

这篇关于在MVC中,视图应该知道模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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