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";
Why not use Person as your model? That way you can use a strongly typed view. My personal opinion is that the ViewBag is pretty much 'magic strings' and while it works well on a small scale where you are the only dev, in larger applications and projects you are pretty much forcing everyone to remember what all the magic strings are. Also, you are not getting type safety which you would using a model and a strongly typed view.
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.