的ViewModels或ViewBag? [英] ViewModels or ViewBag?

查看:159
本文介绍了的ViewModels或ViewBag?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的MVC4,EF5和ASP.Net,我似乎并没有能够在任何地方找到一个很好的答案。

基本上,一切都应该可以通过视图模型做还是确定也纳入viewbag?

说我有一个填充下拉列表的方法,而我使用的是视图模型重新present视图的输出。

我是确定使用 Viewbag.DropDown = PopulateDropdown(); 或会更好合并
这个入视图模型,通过创建一个属性来保存列表< SelectListItem> PopulateDropdown()创建;

我知道怎么ViewBag是得心应手,但我还没有看到任何坚实的理由,以不使用它呢?如果有人还可以提供我一些更深入的了解,这将是非常美妙的。


解决方案

  

基本上,一切都应该可以通过视图模型做还是确定
  也纳入viewbag?


一切都应该视图模型内进行。这是一个视图模型是什么。一个类,您专门定义,以满足您观的要求。不要用的ViewModels混合ViewBags。它不再是清除其中的信息来自何处的看法。要么只使用一个视图模型(方法,我建议)或仅使用ViewBags。但是,不要混用2。

因此​​,在你特殊的例子,你会对你的视图模型属性是类型的IEnumerable< SelectListItem> 和您的视图中,您将使用的强类型版本在Html.DropDownListFor帮手绑定到模型:

  @ Html.DropDownListFor(X => x.ProductId,Model.Products)

显然,那些只是我的2美分。其他人会说,混合的ViewModels和ViewBags是很好,我尊重他们的意见。

I'm fairly new to MVC4, EF5 and ASP.Net, and I don't seem to be able to find a good answer anywhere.

Basically, Should everything be done through the viewmodel or is it Ok to also incorporate viewbag?

Say I have a method which populates a drop down list, and I am using a viewmodel to represent the output for the view.

Am I ok to use Viewbag.DropDown = PopulateDropdown(); or would it be better to incorporate this into the ViewModel, by creating a property to hold the List<SelectListItem> created by PopulateDropdown(); ?

I know how handy ViewBag is, but I'm yet to see any solid reason as to not use it? If anyone could also offer me some more insight, that would be fantastic.

解决方案

Basically, Should everything be done through the viewmodel or is it Ok to also incorporate viewbag?

Everything should be done inside a view model. That's what a view model is. A class that you specifically define to meet the requirements of your view. Don't mix ViewBags with ViewModels. It is no longer clear for the view where is the information coming from. Either use only a view model (approach that I recommend) or only use ViewBags. But don't mix the 2.

So in your particular example you would have a property on your view model which is of type IENumerable<SelectListItem> and inside your view you will use the strongly typed version of the Html.DropDownListFor helper to bind to the model:

@Html.DropDownListFor(x => x.ProductId, Model.Products)

Obviously those are only my 2 cents. Other people will say that mixing ViewModels and ViewBags is fine and I respect their opinion.

这篇关于的ViewModels或ViewBag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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