I make heavy use of the ViewBag in my MVC application, is this considered bad practice? I'm unsure as to whether to spend time creating ViewModels (however I thought that was more suited to MVVM rather than MVC) or continue using the ViewBag heavily. What are the arguments for and against this? Example controller method would return it's model (generally a simple domain entity) as well as the following calls to the ViewBag:
ViewBag.TotalItems = data.Count();
ViewBag.FilteredItems = gridFilters;
ViewBag.Action = "Events";
ViewBag.Area = "People";
ViewBag.EntityID = person.EntityID;
ViewBag.OrganisationID = ID;
ViewBag.Name = string.Format("{0} {1}", person.FirstName, person.LastName);
ViewBag.IsEnabled = person.IsEnabled;
ViewBag.EntityID = person.EntityID;
ViewBag.Favourited = users.IsOnUserFavourites(person.EntityID);
ViewBag.Columns = userColumns;
ViewBag.Title = "Person : " + string.Format("{0} {1}", person.FirstName, person.LastName) + " - Events";
Questions like these will usually get answers from both sides of the fence. Many people feel that using ViewBag like this is a bad design (myself included). It makes your controllers less testable. Your views are not strongly typed, etc.
It is usually a good practice to use a ViewModel
. Instead of have your model be a domain model, create a model that is specific to the view you are displaying. That way it can be 100% custom tailored to what you need for this specific view. You will find that you don't really need to use ViewBag much once you do this. It can sometimes create a lot of extra code (one view model per view) but the code is pretty simple and making a change to one view will not break any others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With