Tuesday, January 21, 2014

What is TempData in MVC?

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value.
The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects.
It internally uses session variables. Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view.
It requires typecasting for complex data type and check for null values to avoid error. generally used to store only one time messages like error messages, validation messages.
 Example::
public ActionResult Index(){
TempData["about"] = "about us";
 return View();
//return RedirectToAction("Welcome","User");//user is acontroller
//return RedirectToAction("About");//about is a actionresult
}
 public ActionResult About(){
 var model = TempData["about"];
return View();
}

 

No comments:

Post a Comment