What is Viewdata, Viewbag & Tempdata and Session in Asp.Net MVC

TempData in asp.net MVC

TempData in asp.net MVC

  • TemData is used to store the temporary data for the subsequent requests.
  • the main use of Tempdata is used to transfer the data from one Action Method to Another Action Method
  • TempData is derived from TempDataDictionary.
  • The Value of TempaData must be Type Cast before use
  • TempData internally uses the session to store the data. so it is a short-lived session.
public class HomeController: Controller

What is VIewBag?

TempData has mainly two method

1.      Keep
2.      Peek

TempData.Keep() has mainly 2 overloaded methods

1.      Void keep is used to all the data should not be deleted on current request completion
2.       Void keep(string key) is used to persist specific item in TempData with help of name

TempData.Peek() has no overloaded methods

1.     it returns an object which contains an item with the specific key without making the key for deletion

Example :

public ActionResult About()
        string Name;
        int City;
        if (TempData.ContainsKey("name"))
            Name = TempData["name"].ToString();
        if (TempData.ContainsKey("city"))
            City = int.Parse(TempData["city"].ToString());

        return View();


No comments: