Heavy use of ViewBag
Asked Answered
N

2

6

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";
Nielsen answered 30/11, 2011 at 15:9 Comment(0)
G
9

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.

Gem answered 30/11, 2011 at 15:32 Comment(2)
Thanks, this was pretty much what I was looking for.Nielsen
Again, remember that questions like these are very subjective. What works for you might not work for others and what works for others might not work for you. I'm just answering from my own point of view :)Gem
A
0

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.

Abbey answered 30/11, 2011 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.