Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - ViewModels or ViewBag?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...