Difference Between ViewData, ViewBag and TempData with Example

Introduction:
In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data from controller to view and in next request. Like WebForm, you can also use Session to persist data during a user session. Now question is that when to use ViewData, VieBag, TempData and Session. Each of them has its own importance. This article explains the differences among ViewData, ViewBag and TempData.

Difference Between ViewData, ViewBag and TempData with Example


ViewData

    1- ViewData is used to pass data from controller to view
    2- It is derived from ViewDataDictionary class
    3- It is available for the current request only
    4- Requires typecasting for complex data type and checks for null values to avoid error
    5- If redirection occurs, then its value becomes null

Example:- 
In controller

public ActionResult Index()
{
    ViewData["Name"] = "Vepsh Tech";
    return View();
} 

In View

@ViewData["Name"]


ViewBag

    ViewBag is also used to pass data from the controller to the respective view
    ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
    It is also available for the current request only
    If redirection occurs, then its value becomes null
    Doesn’t require typecasting for complex data type

Example:-
In Controller 

public ActionResult Index()
{
    ViewBag.Name = "Vepsh Tech";
    return View();
}

In View

@ViewBag.Name 

TempData

    1- TempData is derived from TempDataDictionary class
    2- TempData is used to pass data from the current request to the next request
    3- It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
    4- It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages

Example:-

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); 
}

Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment