我在我的 MVC 应用程序中大量使用 ViewBag,这被认为是不好的做法吗?我不确定是花时间创建 ViewModels(但我认为这更适合 MVVM 而不是 MVC)还是继续大量使用 ViewBag。赞成和反对的论据是什么?示例 Controller 方法将返回它的模型(通常是一个简单的域实体)以及对 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";
最佳答案
像这样的问题通常会从围栏的两边得到答案。很多人觉得像这样使用 ViewBag 是一个糟糕的设计(包括我自己)。它使您的 Controller 的可测试性降低。您的观点不是强类型的,等等。
使用 ViewModel
通常是一个好习惯。 .不要让您的模型成为域模型,而是创建一个特定于您正在显示的 View 的模型。这样,它可以 100% 定制以满足您对该特定 View 的需求。一旦你这样做了,你会发现你真的不需要太多地使用 ViewBag。它有时会创建很多额外的代码(每个 View 一个 View 模型),但代码非常简单,对一个 View 进行更改不会破坏任何其他 View 。
关于asp.net-mvc-3 - 大量使用 ViewBag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8328083/