TempData In ASP.NET MVC

In Web application passing data from one request to another request is very important to perform the some action on data.
In traditional ASP.NET application data passed to the session is stay's long time time in memory as per session timeout defined in the web.config file, But sometime we need to maintain data only for current request instead of all requests and data should be disappears in second request , for this situation session is not fit which maintain the data for all request so we need to use TempData to maintain data for only current request which saves the server memory by releasing the data when second request fires.I hope you understand when to use TempData over session variable.
Before going to learn about TempData, read about the ViewBag and ViewData using following link
Download Aspose : API To Create and Convert Files
What is TempData ? 
TempData is used to pass data from controller to controller and also controller to view for current request.
TempData in ASP.NET MVC by compilemode.com
Key points
  • Used to pass data from controller to controller as well as controller to view.
  • It holds the Data for short time means till current request.
  • TempData internally uses session variable to hold the values during request.
  • TempData is the object of ViewDataDictionary class.
  • We need to handle null otherwise if  TempData value is null and we tried to access value then it throws the exception.
  • The value assigned to TempData is only available for single request, if again new request initiated then value will become null.
  • It is  property of ControllerBase class.
  •  It’s  require type conversion such as int to string or string to int etc . 
Example
We can assign the value to the TempData in the following way
//Assigning value to TempData
 TempData["CityName"] = "Latur";
In the above code CityName is the key and Latur is the value for TempData object.
Accessing TempData value in View
<div>
@TempData["CityName"]
</div>
In the above way we can access the TempData value into the view.
Accessing TempData value in Controller Action method
    public ActionResult CheckTempValue()
        {
           //Reading the values of TempData
            var TempName = TempData["EmpName"].ToString();
            return View();
        }
In the above way we can access the TempData value into the controller.
Summary
I hope this article is useful for all readers . If you have a suggestion related to this article then please contact me.

Related ASP.NET MVC Article .

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode