放什么在你的视图模型 [英] What to put in your ViewModel

查看:146
本文介绍了放什么在你的视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

和你放什么看法?

最近<一个href=\"http://www.hanselman.com/blog/IPrincipalUserModelBinderInASPNETMVCForEasierTesting.aspx\">blog从斯科特Hanselman的了解采用特殊的模型绑定,方便测试使我思考如下:
你把什么在你的控制器逻辑构建视图模型,哪些应放在有何看法?他所做的是这样的:

A recent blog from Scott Hanselman about using a special model binder for easier testing led me to think about the following: What do you put in your controller logic building the view model, and what should be put in the view? what he does is this:

var viewModel = new DinnerFormViewModel {  
    Dinner = dinner,  
    Countries = new SelectList(PhoneValidator.Countries, dinner.Country)  
};  
return View(viewModel);

现在,我用数据传递给我的看法相同的方式,但我不确定他是如何与国家房地产交易。你可以说双方:
包装在选择列表$ P $的国家名单ppares视图的数据,就像你创建一个视图模型DTO来传递数据。
在另一方面,它在某种程度上感觉就像你具体操作的下拉列表中使用的数据,限制的方式从控制器的数据视图交易。
我觉得这是一个有点上的视图和控制器之间的关系分离的灰色地带,我真的不能确定哪个方向走。是否有任何的最佳做法吗?

Now, I use the same way of passing data to my view, but I am unsure about how he deals with the Countries property. You could argue both sides: Wrapping the Countries list in the SelectList prepares the data for the view, much like you create a viewmodel DTO to pass your data. On the other hand, it somehow feels like you're specifically manipulating the data to be used in a dropdown list, limiting the way the view deals with your data from the controller. I feel this is a bit of a gray area on the separation of concerns between the view and the controller, and I can't really decide which way to go. Are there any best practices for this?

PS:为了简单起见,我们假设默认的ASP.NET MVC的背景下,所以基本上你的盒子项目出来。默认视图引擎和所有的爵士乐。

PS: To keep it simple, let's assume the default ASP.NET MVC context, so basically your out of the box project. Default view engine and all that jazz.

推荐答案

在MVC(至少是这个味道吧),管制员的职责之一就是prepare视图的数据。所以,我认为这是ppare为意味着它将在一个下拉使用的意见消耗一个特定的模式完全可以接受的$ P $。在这种情况下,所述控制器被刚好使它更容易为视图和实际上prevents别扭code来自具有以其它方式被滴入图。它还保留一个不必像VieData [国家]在ViewData的那些神奇的字符串。

In MVC (at least this flavor of it), one of the controller's responsibilities is to prepare the data for the view. So I think it is perfectly acceptable to prepare a specific model for the views consumption that implies it will be used in a drop-down. In this case the controller is just making it easier for the view and in fact prevents awkward code from having to otherwise be trickling into the view. It also keeps one from having those magic strings in the ViewData like VieData["Countries"].

所以,综上所述,虽然它可能似乎没有在职责方面存在一些灰色地带,最终是控制器的工作:与视图互动并变换域模型到更易于其他车型由视图消耗。

So to sum up, while it may seem that there is some gray area in terms of responsibilities, ultimately that is the job of the controller: to interact with the view and to transform the domain model into other models that are easier to consume by the view.

这篇关于放什么在你的视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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