ViewModel 还是 ViewBag? [英] ViewModels or ViewBag?

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

问题描述

我对 MVC4、EF5 和 ASP.Net 还很陌生,我似乎无法在任何地方找到好的答案.

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

基本上,一切都应该通过 viewmodel 完成还是也可以合并 viewbag?

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.

我可以使用 Viewbag.DropDown = PopulateDropdown(); 还是合并会更好通过创建一个属性来保存由 PopulateDropdown(); ?

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(); ?

我知道 ViewBag 有多方便,但我还没有找到任何不使用它的可靠理由?如果有人还可以为我提供更多见解,那就太棒了.

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.

推荐答案

基本上,一切都应该通过视图模型完成还是可以还要加入viewbag?

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

一切都应该在视图模型中完成.这就是视图模型.为满足视图要求而专门定义的类.不要将 ViewBags 与 ViewModels 混合使用.信息来自何处的视图不再清晰.要么仅使用视图模型(我推荐的方法),要么仅使用 ViewBags.但不要混用 2.

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.

因此,在您的特定示例中,您的视图模型上将有一个 IENumerable 类型的属性,并且在您的视图中,您将使用 Html.DropDownListFor 助手的强类型版本绑定到模型:

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)

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

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

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

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