Original source: Http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-cplusViewBagplusandplusTem
ASP. NET MVC provides 3 choices of viewdata,viewbag,tempdata to transfer data from controller to view and subsequent requests.
ViewData and ViewBag are very similar, while tempdata are different.
Let's discuss or summarize the main points of the three:
The difference between ViewBag and ViewData:
- ViewData is a Dictionary object that inherits from the Viewdatadictionary class and has a string (string) that accesses the object as a key.
- ViewBag is a dynamic property and is a good dynamic feature added by c#4.0.
- ViewData requires a data type conversion to determine whether the book is null to prevent errors.
4.ViewBag does not require a type conversion.
Examples of ViewBag & ViewData:
Public ActionResult Index () { "monjurul Habib"; return View ();}
Public ActionResult Index () { viewdata["Name""Monjurul Habib"; return View ();}
In the View:
@ViewBag. Name @ViewData ["name"]
TempData:
TempData is also a dictionary type, inherited from the Tempdatadictionary class. stored in a short session. The key is of type string and the value is type object.
The difference is the life cycle of the object. The TempData color life cycle is the time of an HTTP request. It means the time to jump from one page to another. Keep 302/303 redirected because they are in the same request.
Save your data when you jump from one control to another control or one page to another page. It uses the session mechanism internally. It is used primarily to store data during jumps from one page to another.
Data type conversions are required to check for NULL to circumvent errors. Typically used to store a time information, error message, or authentication information.
PublicActionResult Index () {varModel =NewReview () {Body="Start", Rating=5 }; tempdata["modelname"] =model; returnRedirecttoaction (" About");}<pre><pre lang="CS"> PublicActionResult About () {varModel= tempdata["modelname"]; returnView (model);}
The last mechanism is the session, working like ViewData, dictionary type, such as key-value mode, the key is generally string type, the value can be the object type. In this way, the data is stored in the client's cookie and can be kept for a longer period of time. Row validation is also required, but there is no security guarantee. About ViewData and viewbag you need a more flexible should be shipped in the program. Because each page moves through the entire life cycle of the ASP. You can use Viewdata/viewbag in a sub-page, but be careful that you are not using it to populate irrelevant data and contaminate your controller.
What are ViewData, ViewBag and TempData? -MVC three ways to pass data between current and subsequent requests