The difference between MVC ViewBag and ViewData

Source: Internet
Author: User


At the beginning of MVC3, view data can be accessed through the ViewBag property, and ViewData is used in MVC2. The use of ViewData is preserved in the MVC3. ViewBag is a dynamic type, ViewData is a word typical (Dictionary).
They are defined as follows:

Public dynamic ViewBag {get;} Public viewdatadictionary ViewData {get; set;}

Code in Controller:

Public ActionResult Index () {viewbag.message_viewbag = "I am ViewBag"; viewdata["Message_viewdata"] = "I am ViewData"; return View ();}

View Code:

@{viewbag.title = "Home";} 

Operation diagram:

Of course we can write this in the view:

The result is the same, which means that they are both interconnected.

The difference between ViewBag and ViewData:
ViewBag is no longer a dictionary's key-value pair structure, but dynamic type, which is parsed dynamically when the program is run.
Using ViewBag
Controller code:

Public ActionResult Index () {string[] items = new string[] {"One", "one", "three"}; Viewbag.items = items;//ViewBag is a new dynamic keyword for the wrapper//viewdata["Items"] = Items;return View ();}


View Code:

<ul> @foreach (Dynamic p in Viewbag.items) {<li>the item is: @p</li>}</ul>

Where dynamic p can be substituted with var p or string p
Execution effect:

If you use ViewData, the following error occurs:

At this point, if we want to use viewdata, we need to manually cast it to an array. By debugging, we can see

string[] items = new string[] {"One", "one", "three"}; Viewbag.items = Items; viewdata["Items" = items;

The ViewBag and ViewData after assignment are all in the form of string arrays. Such as:

Only ViewData is an object type, and ViewBag is a dynamic type. The difference between the dynamic type and the object type is that it is automatically converted according to the data type when used, and the object type requires us to cast it ourselves. For example, when we traverse Viewbag.items, it is automatically converted according to the data type, while ViewData requires us to cast, as follows:

@foreach (String A in (string[]) viewdata["Items"]) {<li>the item is: @a</li>}

In addition, by going to the definition we can see:

[Dynamic]public Dynamic ViewBag {get;} Public viewdatadictionary ViewData {get; set;}

Here ViewBag only get method, there is no set method, but we in the above give ViewBag assignment. Pass
The ViewBag code for the Anti-compilation discovery is as follows:

[Dynamic]public object Viewbag{[return:dynamic]get{func<viewdatadictionary> viewdatathunk = null;if (this._ Dynamicviewdatadictionary = = null) {if (Viewdatathunk = = null) {Viewdatathunk = () = =. ViewData;} This._dynamicviewdatadictionary = new Dynamicviewdatadictionary (viewdatathunk);} return this._dynamicviewdatadictionary;}}

It is not difficult to see ViewBag return is _dynamicviewdatadictionary, continue to trace the discovery _dynamicviewdatadictionary belongs to the Dynamicviewdatadictionary class, its code is as follows:

Internal sealed class dynamicviewdatadictionary:dynamicobject{//fieldsprivate readonly func<viewdatadictionary > _viewdatathunk;//methodspublic dynamicviewdatadictionary (func<viewdatadictionary> viewDataThunk); public override Ienumerable<string> Getdynamicmembernames ();p ublic override bool Trygetmember (GetMemberBinder Binder, out object result);p ublic override bool Trysetmember (SetMemberBinder Binder, object value);//Propertiesprivate V Iewdatadictionary ViewData {get;}} There are Trygetmember and Trysetmember methods, which point to the two methods: public override bool Trysetmember (SetMemberBinder Binder, Object value) {this. Viewdata[binder. Name] = Value;return true;} public override bool Trygetmember (GetMemberBinder binder, out object result) {result = this. Viewdata[binder. Name];return true;}

found that viewbag in fact is the essence of viewdata, but more layers of dynamic control. So, the way you use it depends entirely on your personal interests.

Use of TempData
Like ViewData and ViewBag, TempData can also be used to pass data to a view. Just ViewData and ViewBag have the same life cycle as view and are only useful for the current view. The tempdata can be transmitted in different action, similar to the seesion in WebForm. As follows:

Public ActionResult Index () {Viewbag.hello = ' hello,this is ViewBag '; viewdata["HI"] = "hi,this is ViewData"; tempdata["abc"] = "This is TempData"; return View ();}

Then, in the About view, call:

The page works as follows:

Only the value of tempdata["ABC" is obtained, but the value of TempData is automatically deleted after it is taken once, and then when I refresh the page, the tempdata["ABC" is null. View the code by deserializing it and discover that the TempData data is automatically deleted after it is called. For more information, see: http://www.cnblogs.com/tristanguo/archive/2009/04/06/1430062.html

Additional View considerations:

<li>the item is: @Html. Raw (p) </li> indicates that P is not Html-encoded.

The controller can return to this view or return to another view:
Public ActionResult Index ()
{
Viewbag.message_viewbag = "I am ViewBag";
viewdata["Message_viewdata"] = "I am ViewData";

Return View ("about");
}
When we need to return a view that specifies a completely different directory structure, you can use the ~ symbol to provide the full path to the view to return: Return view ("~/views/home/about.cshtml");

The difference between MVC ViewBag and ViewData

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.