什么样的数据属于视图模型?
“视图模型”这个名称表明它对视图的数据进行建模。这是显而易见的。视图模型中还可以或应该包含哪些内容?
例如,视图可能显示购物车中的商品列表、客户信用卡信息字段以及客户账单信息字段。视图模型可能包含所有这些的属性,或者可能只包含购物车项目的属性。
The name "view model" suggests that it models the data for the view. That much is obvious. What else can or should go in the view model?
As an example, a view might display a list of items in a shopping cart, fields for customer's credit card info, and fields for customer's billing information. The view model might contain properties for all that OR it might only contain properties for the shopping cart items.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
视图模型是一个类,表示视图显示/修改的字段。因此,例如,如果您要在同一页面上显示购物车和客户的信用卡,那么这些属性都应该属于视图模型。
如果视图要显示日期名称的下拉列表,您甚至可以在视图模型中放置这样的属性:
The view model is a class that represents the fields that your view shows/modifies. So for example if you are going to show a shopping cart and customer's credit card all on the same page these properties should all belong to the view model.
You could even put properties like this in your view model if the view is going to show a drop down list of day names:
究竟如何使用视图模型取决于判断。一名开发人员可能拥有较少的类型化 ViewModel,以便可以重用它们。另一个开发人员可能有更多的 ViewModel,每个 ViewModel 都更小并且更具体地针对特定操作。而另一个开发人员可能更依赖 ViewData。
如果可能的话,让您的视图模型组织良好,仅包含视图所需的内容,并且主要由轻实体对象组成。如果您有一个复杂的视图,请不要害怕创建一个高度自定义的视图模型类,这将有助于简化视图逻辑。制作可重用的 ViewModel,其中包含一些未使用的数据是可以的,但要避免仅使用一些一刀切的 ViewModel。 ViewModel 应该只包含该视图所需的数据或非常接近的数据。
How exactly you use your view models is a judgement call. One developer might have fewer typed ViewModels so they can be reused. Another developer might have more ViewModels, each smaller and more specific to particular actions. And another developer might rely more on ViewData.
If possible, have your view models be well-organized, contain just what the view needs, and consist mostly of light entity objects. If you have a complicated view though, don't be afraid to make a highly customized view model class that will help simplify the view logic. It's okay to make reusable ViewModels that have a little unused data in them, but avoid using just a few one-size-fits-all ViewModels. ViewModels should have just the data needed for that view or very close.