tempdata in asp.net mvc
TempData
is a dictionary-like object that is available in ASP.NET MVC and can be used to store data between two consecutive requests. Unlike ViewData
and ViewBag
, TempData
persists data across redirects.
Here's how to use TempData
in ASP.NET MVC:
- In the controller, add the data you want to store to the
TempData
dictionary using a key-value pair. For example:
public ActionResult MyAction() { TempData["Message"] = "Welcome to my page!"; return RedirectToAction("OtherAction"); } public ActionResult OtherAction() { string message = TempData["Message"] as string; ViewBag.Message = message; return View(); }
In the first action, you can add data to the
TempData
dictionary and redirect to another action. In the second action, you can retrieve the data from theTempData
dictionary and pass it to the view usingViewBag
.To retrieve data from
TempData
, you need to cast it to the appropriate type. If the key is not found in theTempData
dictionary,null
will be returned.When you retrieve data from
TempData
, it is removed from the dictionary, so you can only access it once. If you need to access the same data multiple times, you should store a copy of it in another variable.By default,
TempData
uses session state to store data. However, you can configure it to use other providers, such as cookies or database.
TempData
is useful when you need to store data between two consecutive requests, such as after a redirect. However, you should use it sparingly, as it uses session state, which can affect performance and scalability. If possible, use other mechanisms, such as query strings or model binding, to pass data between actions.