ViewData, ViewBag, and TempData are the three ways in which data may be passed from the controller to the view in ASP.NET MVC.in this post I will explain how these thee differ from one another.
ViewData
- Used to pass data from controllers to views.
- A pair of keys and values is used to transfer data.
- It requires typecasting for getting data and checking for null values to avoid errors.
- Its existence is limited to the duration of the current request.
//Controller Code
public ActionResult Index()
{
ViewData[“Message”] = “Welcome to debug.to”;
return View();
}
//View code
<h3> @ViewData[“Message”] </h3>
ViewBag
- It does not require typecasting for getting data.
- Used to pass data from controllers to views.
- Has a short life means once it passed value from controllers to views, it becomes null.
//Controller Code
public ActionResult Index()
{
ViewBag.Message = “Welcome to debug.to”;
return View();
}
//View code
<h3> @ViewBag.Message </h3>
TempData
The primary purpose of TempData is the transfer of values between controllers or between actions within the same controller.It is most useful when you redirect one page to another page and want to send some information along with it.
- Must check for null values to avoid errors.
- A pair of keys and values is used to transfer data.
- TempData is alive in two subsequent request. It uses TempData.Keep() method for third request.
//Controller Code
public ActionResult Index()
{
TempData[“Message”] = “Welcome to debug.to”;
return View();
}
public ActionResult About()
{
if(TempData["Message"] != null)
{
TempData.Keep();
return RedirectToAction("Contact");
}
return View();
}
//View code
if (TempData["Message "] != null)
{
msg = TempData["Message "].ToString();
}