What is TempData property in MVC2


In this article we will see what is the use of TempData property in MVC2. The TempData property is used to pass data between different action methods in MVC2. The advantage of TempData object is that its value is persisted across multiple requests.

In this article we will see what is the use of TempData property in MVC2.

The TempData property is used to pass data between different action methods in MVC2. In some cases an ActionMethod might need to pass data to another Action Method.

Every controller maintains a "TempDataDictionary" object which can be used
to store data before it calls another action method using its RedirectToAction method. The method that is being called can now use
the value from this "TempDataDictionary" object because this value is stored in session state. The TempData value persists either till the session times out or untill it is read. The value in TempData is persisted across multiple requests.

Below example shows a data class that is used to rectify an error and to pass the data between actions.


public class ErrorInfo
{
public string ErrorMessage { get; set; }
public string EmpName{ get; set; }
}


public class EmployeeController
{
...
public ActionResult InsertEmployee(string empName)
{
if (String.IsNullOrEmpty(empName))
{
ErrorInfo errorInfo = new ErrorInfo();
errorInfo.ErrorMessage = "Please provide Employee Name";
errorInfo.EmpName = empName;
TempData["error"] = errorInfo;
return RedirectToAction("NewEmployee");
}
// In case of no errors
...
return View();
}

public ActionResult NewEmployee()
{
ErrorInfo err = TempData["error"] as ErrorInfo;
if (err != null)
{
// If the previous action resulted in an error,capture it for display.
ViewData["EmpName"] = err.EmpName;
ViewData["ErrorMessage"] = err.ErrorMessage;
}
return View();
}


You can dispay the error message using below code:

<% if (ViewData["ErrorMessage"] != null) { %>
Error while inserting the Employee Information for
<%=ViewData["EmpName"] %> :
<br />
<%= ViewData["ErrorMessage"] %>
<br />
<% } %>


Article by Vaishali Jain
Miss. Jain Microsoft Certified Technology Specialist in .Net(Windows and Web Based application development)

Follow Vaishali Jain or read 127 articles authored by Vaishali Jain

Comments

Author: Umesh Bhosale26 Mar 2014 Member Level: Silver   Points : 2

1. TempData is a dictionary object that is derived from
2. It has short lives session.
3. TempData is used to pass data from current request to subsequent request
4.It's life is very short and lies only till the target view is fully loaded.
5.It need type casting for checking null value for avoiding Null value exceptions



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: