How to persist data in TempData?

The life of TempData is very short and lies only till the target view is fully loaded. But you can persist data in TempData by calling Keep() method after request completion

  • void Keep() – Calling this method with in the current action ensures that all the items in TempData are not removed at the end of the current request.
    public ActionResult Index() {
    	ViewBag.Message = TempData["Message"];
    	Employee emp = TempData["emp"] as Employee; //need type casting
    	TempData.Keep(); //persist all strings values
    	return View();
    }
  • void Keep(string key) – Calling this method with in the current action ensures that specific item in TempData is not removed at the end of the current request.
    public ActionResult Index() {
    	ViewBag.Message = TempData["Message"];
    	Employee emp = TempData["emp"] as Employee; //need type casting
    	//persist only data for emp key and Message key will be destroy
    	TempData.Keep("emp");
    	return View();
    }
Tagged , . Bookmark the permalink.

Leave a Reply