TempData

ViewBag or ViewData can be passed only from a controller's action to view, its not passed from one action to another action.

You can redirect the control from one action to another action using the method RedirectToAction(<<actionName>>, <<controller>>)

Syntax of TempData is very similar to ViewData

public class HomeController: Controller{
 public ActionResult Index(){
     TempData["MyOriginalData"] = "Data from Index action"; // this data will preserved and available in the below action when we are redirected by below code line
     return RedirectToAction("Home", "Home");
 }

 public ActionResult Home() {
     //TempData["MyOriginalData"]  is available and hence can be used in Home view
     return View();
 }
}

Using TempData in View

<div>
    My data  I received from controller is: 
    @TempData["MyOriginalData"]
</div>

To maintain data form complete request i.e. from one action to another to the view, use TempData.

Peek and Keep

TempData helps to maintain data to preserve or persist data for the next request if any of the below 3 conditions is met:

Lets say we have a value "Val1" in TempData set in some Controller action:

....
    TempData["Val1"] = "Value 1";
....
  1. If the Tempdata value is not used or read in View, the value in the TempData would persist in the next session request from client to next to next until its value is read in some view.

  2. If the Tempdata value is read in a View and then Temp.Keep("Val1") is called, then the value of TempData would be preserved for the next session request.

    View code:

    <div>
     Val1 value is @TempData["Val1"]
     @{
         TempData.Keep("Val1");
     }
    </div>
  3. If instead of reading the value of TempData in line in the HTML, is its value is used using TempData.Peek("Val1"), then TempData value would be preserved for the next session request.

View code:

<div>
@{
    string str1 = TempData.Peek("Val1");
}
Val1 value is  @str
</div>

Last updated

Was this helpful?