Heavy use of ViewBag

I am actively using ViewBag in my MVC application, is this considered bad practice? I am not sure whether to spend time creating ViewModels (however, I thought it was more suitable for MVVM, not MVC) or to continue to use ViewBag heavily. What are the arguments for and against this? An example controller method returns its model (usually a simple domain object), as well as the following ViewBag calls:

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"; 
+6
source share
2 answers

Such questions will usually be answered on both sides of the fence. Many people find that using ViewBag seems like a bad design (including me). This makes your controllers less verbose. Your views are not very typified, etc.

It is generally recommended to use ViewModel . Instead of making your model a domain model, create a model specific to your view. Thus, it can be 100% completed taking into account what you need for this particular type. You will find that you really don't need to reuse the ViewBag once you do this. Sometimes this can create a lot of additional code (one view model for each view), but the code is quite simple and changing one view will not break the others.

+9
source

Why not use Person as your model? This way you can use a strongly typed view. My personal opinion is that the ViewBag is pretty much the magic line, and although it works well on a small scale, where you are the only developer, in large applications and projects you pretty much make everyone remember what all magic is strings. In addition, you do not get type safety that would use a model and a strongly typed view.

0
source

Source: https://habr.com/ru/post/902755/


All Articles