Sometimes, we may need to pass some data from one action method to another while redirecting the user to another action method. In this case, we can pass certain data through the RedirectToAction
method by objectParamter. However, there might be scenario where data may not fit in the objectParamter as those parameter must be defined into the action method we want to call.
In this kind of scenario, we can use TempData
.
CONTROLLER CODE
public ActionResult Index() { // once the value i set, we will need to use it otherwise it // remains in the memory and next time when this action method will be called // it throws error "key already exists" error TempData.Add("MyTempData", "This data is coming from calling method."); return RedirectToAction("TempDataMethod"); // Below action method will be called } public ActionResult TempDataMethod() { return Content(TempData["MyTempData"].ToString()); }
TempData
accepts the value in key and value pair. Value can be any type of object (not necessarily string or integer but it can be class or collection of classes or any different types of object).
When above Index action method is called, it saves the data into TempData with the key “MyTempData” and redirects to the “TempDataMethod” action method.
TempDataMethod is accessing the TempData saved into Index method by specifying its key and returning to the View.
POINT OF INTEREST
System.ArgumentException: An item with the same key has already been added.
Keep
or Peek
methods.string data = TempData["MyTempData"].ToString();
TempData.Keep("MyTempData"); // above like is mandatory
string data = TempData.Peek("MyTempData").ToString();