Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
908 views
in Blog Post by 20 36 42
edited by

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

  1. Used to pass data from controllers to views.
  2. A pair of keys and values is used to transfer data.
  3. It requires typecasting for getting data and checking for null values to avoid errors.
  4. 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

  1. It does not require typecasting for getting data.
  2. Used to pass data from controllers to views.
  3. 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. 

  1. Must check for null values to avoid errors.
  2. A pair of keys and values is used to transfer data.
  3. 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();
    }

 


If you don’t ask, the answer is always NO!
...