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.
5.ViewBag and Viedata can only be used in one action method, two Aciton with the same name is still the meaning of 2, not a Aciton method
Examples of ViewBag & ViewData:
public ActionResult Index()
{
ViewBag.Name = "Monjurul Habib";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Monjurul Habib";
return View();
}
@ViewBag.Name
@ViewData["Name"]
TempData:
This seems to be a different action function to use, if not in the same action function!
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 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.
public ActionResult Page()
{
TempData["v"] = "jingya";
return View();
}
public ActionResult Rank()
{
return Content(TempData["v"].ToString());
}
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.
public ActionResult Index()
{
ViewBag.name = TempData["name"];
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
TempData["name"] = "jingya";
return RedirectToAction("Index");
}
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.
From for notes (Wiz)
Asp.net-viewbag Viewdata TempData