Heavy use of ViewBag

限于喜欢 提交于 2019-12-19 06:57:34

问题


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";

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8328083/heavy-use-of-viewbag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!