ASP.NET MVC offers us three options ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility.
Similarities between ViewBag & ViewData :
- Helps to maintain data when you move from controller to view.
- Used to pass data from controller to corresponding view.
- Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.
Difference between ViewBag & ViewData:
- ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
- ViewData requires typecasting for complex data type and check for null values to avoid error.
- ViewBag doesn’t require typecasting for complex data type.
ViewBag & ViewData Example:
public ActionResult Index()
{
ViewBag.Name = "Arun Prakash";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Arun Prakash";
return View();
}
View
@ViewBag.Name
@ViewData["Name"]
TempData:
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. TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only
The only scenario where using TempData will reliably work is when you are redirecting. This is because a redirect kills the current request (and sends HTTP status code 302 Object Moved to the client), then creates a new request on the server to serve the redirected view.
It requires typecasting for complex data type and check for null values to avoid error.
public ActionResult Index()
{
var model = new Review()
{
Body = "Start",
Rating=5
};
TempData["ModelName"] = model;
return RedirectToAction("About");
}
public ActionResult About()
{
var model= TempData["ModelName"];
return View(model);
}
View State in MVC
ASP.NET MVC does not have ViewState (that of storing the values of controls in the web page).
So ASP.NET MVC pages are incredibly lightweight and your request and response times are much faster.
Alternative to View State in MVC
1. For retaining the values during postback in the MVC page values you can use Ajax, so that values in the control won't clear.
2. For temporarily storing the value in current and the subsequent requests use TempData.