Tempdata in MVC




Tempdata is used to share data from controller to its corresponding view as well as its redirects. Tempdata is TempDataDictionary type object, which stores its value in key-value format and store as object type. Therefore, we need to perform type casting while retrieving it.

Example of Tempdata

In the following example, we have created Home Controller and two actions Index and show. From index action, we will redirects to show action. We have created teampdata on index action, which we want to access on show action. Therefore, we will use keep method to store it and we can access it on both index view and show view.


public class HomeController : Controller
    {
        public ActionResult Index()
        {
            TempData["k1"] = "durgesh singh";
            TempData.Keep("k1");
            return View();
        }
        public ActionResult show()
        {
            return View();
        }

    }
  

Tempdata internally use session to store data but it will be destroyed after the completion of subsequent request. We need not to destroy it manually like session.

No comments:

Post a Comment