ViewModels or ViewBag?

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.

Leave a Comment