TempData in MVC with Best Top 2 Example

TempData in MVC is used to transfer data from view to controller, controller to view, or from one action method to another action method of the same or a different controller.

In this article, I am going to discuss the ideas about TempData in MVC with example. Please read our previous articles before moving on to this article where we discussed the ViewModel in MVC. We are going to discuss the following contents which are related to TempData in MVC.

TempData in MVC

  • TempData is a dictionary object and it is property of controllerBase class.
  • It requires typecasting for the complex object.
  • TempData is used to pass data between two consecutive requests.
  • TempData only works during the current and subsequent request.
  • TempData is introduced in MVC 1.0 but It also works with MVC 1.0 and above.
public TempDataDictionary TempData { get; set; }

TempData in ASP.NET MVC with String Type

EmployeeController.cs

public class EmployeeController : Controller
{
	public ActionResult Index ( )
	{
		TempData["Name"] = "www.infosyntax.com";
		return View();
	}
}

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>

<h2>Welcome to @TempData["Name"]</h2>

Output –

ViewData in MVC
TempData in MVC with simple string data

TempData in ASP.NET MVC with Complex Type

EmployeeController.cs

public class EmployeeController : Controller
{
	public ActionResult Index ( )
	{
		TempData["Name"] = "www.infosyntax.com";
		return View();
	}
	
	public ActionResult ComplexIndex ( )
	{
		List Employee = new List();
		Employee.Add("King");
		Employee.Add("Lipsh");
		Employee.Add("Rio");
		TempData["Employee"] = Employee;
		return View();
	}	
}	

ComplexIndex.cshtml

@{
    ViewBag.Title = "ComplexIndex";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
Complex Index</h2>
<ul>
@foreach (var employee in TempData["Employee"] as List)
{
    <li>@employee</li>
}
</ul>

Output –

TempData in MVC
TempData in MVC with Complex data

Warm UP – TempData in MVC

  • TempData is a dictionary object and it is property of controllerBase class.
  • It requires typecasting for the complex object.
  • TempData is used to pass data between two consecutive requests.
  • TempData only works during the current and subsequent request.
  • TempData is introduced in MVC 1.0 but It also works with MVC 1.0 and above.

ViewData from Microsoft

Leave a Comment

Your email address will not be published. Required fields are marked *