码迷,mamicode.com
首页 > 其他好文 > 详细

viewbag

时间:2019-09-10 13:29:20      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:nsf   ase   ORC   variant   exp   problems   adl   absolute   method   

How does ViewBag in ASP.NET MVC work behind the scenes?

https://stackoverflow.com/a/16950197/3782855

ViewBag is a property of ControllerBase. It is defined as follows:

public Object ViewBag { get; }

Note that this signature is actually incorrect. Here‘s what the source code actually looks like:

public dynamic ViewBag {
        get {
            if (_dynamicViewDataDictionary == null) {
                _dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);
            }
            return _dynamicViewDataDictionary;
        }
    }

_dynamicViewDataDictionary is an ExpandoObject; you can add properties to it at runtime. Its lifetime is the same as that of the controller, which is the lifetime of the HTTP request.

 

https://stackoverflow.com/a/16950006/3782855

ViewBag is a property of ControllerBase, which all controllers must inherit from. It‘s a dynamic object, that‘s why you can add new properties to it without getting compile time errors.

It‘s not static, it‘s a member of the object. During the request lifetime, the controller instance is created and disposed, so you won‘t have "concurrency" problems, like overwriting the value.

The View (and its variants) method is not static as well, and this is how the view receives the ViewBag values: during the process of rendering the view, the controller instance has its ViewBag instance as well.

 

MVC ViewBag Best Practice

ViewBag is a dynamic dictionary.

So when using ViewBag to transfer data between action methods and views, your compiler won‘t be able to catch if you make a typo in your code when trying to access the ViewBag item in your view. Your view will crash at run time :(

 

Generally it is a good idea to use a view model to transfer data between your action methods and views.

view model is a simple POCO class which has properties specific to the view.

So if you want to pass some additional data to view, Add a new property to your view model and use that.Strongly typed Views make the code cleaner and more easy to maintain.

With this approach, you don‘t need to do explicit casting of your viewbag dictionary item to some types back and forth which you have to do with view bag.

public class ProductsForCategoryVm
{
  public string CategoryName { set;get; }
  public List<ProductVm> Products { set;get;}    
}
public class ProductVm
{
  public int Id {set;get;} 
  public string Name { set;get;}
}

And in your action method, create an object of this view model, load the properties and send that to the view.

public ActionResult Category(int id)
{
  var vm= new ProductsForCategoryVm();
  vm.CategoryName = "Books";
  vm.Products= new List<ProductVm> {
     new ProductVm { Id=1, Name="The Pragmatic Programmer" },
     new ProductVm { Id=2, Name="Clean Code" }
  }
  return View(vm);
}

And your view, which is strongly typed to the view model,

@model ProductsForCategoryVm
<h2>@Model.CategoryName</h2>
@foreach(var item in Model.Products)
{
    <p>@item.Name</p>
}

 

Dropdown data ?

A lot of tutorials/books has code samples which uses ViewBag for dropdown data.

I personally still feel that ViewBag‘s should not be used for this.

It should be a property of type List<SelectListItem> in your view model to pass the dropdown data.

Here is a post with example code on how to do that.

Are there situations where a ViewBag is absolutely necessary?

There are some valid use cases where you can(not necessary) use ViewBag to send data.

For example, you want to display something on your Layout page, you can use ViewBag for that.

Another example is ViewBag.Title (for the page title) present in the default MVC template.

注意ViewBag.AnnouncementForEditors的使用,AnnouncementForEditors是直接加到dynamic类型的ViewBag上的。

public ActionResult Create()
{
   ViewBag.AnnouncementForEditors="Be careful";
   return View();
}

And in the layout, you can read the ViewBag.AnnouncementForEditors

因为后端代码,加了对应的属性,所以在前端代码里可以直接使用

<body>
<h1>@ViewBag.AnnouncementForEditors</h1>
<div class="container body-content">
    @RenderBody()
</div>
</body>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

viewbag

标签:nsf   ase   ORC   variant   exp   problems   adl   absolute   method   

原文地址:https://www.cnblogs.com/chucklu/p/11496862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!