TempData in MVC
TempData allows you to store data & it will remain after redirects. It uses the Session to store data. When an object in a TempDataDictionary. It will be marked for deletion at the end of that request.
TempData declared as
Example
TempData.Clear() : It is use to remove all keys from the TempDataDictionary TempData.Remove(key) :Remove a specific key from TempDataDictionary.
Note: Since TempData makes use of the Session State behavior, it must be enabled on the controller using TempData. By default it is always enabled, You can disable session state for your controllers by adding [SessionState(SessionStateBehavior.Disabled)] attribute .
TempData declared as
TempData["value"] = "data";
Example
public ActionResult FirstAction()
{
// store something into the tempdata that will be available during a single redirect
TempData["FirstAction"] = "SecondAction";
// you should always redirect if you store something into TempData to
// a controller action that will consume this data
return RedirectToAction("SecondAction");
}
public ActionResult SecondAction()
{
var data = TempData["FirstAction"];
return View();
}
The Peek and Keep methods allow to read the value without deletion. we can say that first request data will remains in TempData. You can use Peek when you always want to retain the value for another request. Use Keep when retaining the value depends on additional logic.
//second request, Peek value is not deleted at the end of the request
object value = TempData.Peek("value");
//third request, read value and delete
object value = TempData["value"];
Keep
//second request, get value going for delete
object value = TempData.["value"];
//later decide to keep it for next request
TempData.Keep("value");
//third request, read value and mark it for deletion
object value = TempData["value"];
Removing TempDataTempData.Clear() : It is use to remove all keys from the TempDataDictionary TempData.Remove(key) :Remove a specific key from TempDataDictionary.
Note: Since TempData makes use of the Session State behavior, it must be enabled on the controller using TempData. By default it is always enabled, You can disable session state for your controllers by adding [SessionState(SessionStateBehavior.Disabled)] attribute .
0 comments :
Post a Comment