Introduction
TempData is a key-value pair Dictionary or other words its dictionary object stored in a temporary variable. Most of the time developer wants to transfer data from controller to view or controller to controller. By using tempData you can store the list and pass it to view or controller as per the developer requirement.
TempData actually sends the live data between HTTP requests, in other words, tempData keeps data between the HTTP request. TempData is available only for subsequent and current requests.
How To Use TempData Keep And Peek In MVC
Everyone knows in MVC tempdata lifetime is only for subsequent or current requests. Keep and Peek use to preserve the data for the next request.
How To Store List In TempData In MVC
Suppose their list of the city name and want to transfer to view or another controller that time you need tempdata.
Now we learn how to store lists in tempdata in MVC step by step from scratch.
1.Create MVC Project in visual studio 2019.
2.Add Class in models folder like employee.cs .
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
3.Add Employee Controller
4.Creating employee list in the action method
public ActionResult Index()
{
List<Employee> emp = new List<Employee>() {
new Employee(){ EmployeeId=1, Name="Rudra", Gender="Male", City="Kandhar"},
new Employee(){ EmployeeId=2, Name="Sachin", Gender="Male", City="Nanded"},
new Employee(){ EmployeeId=3, Name="Kailas", Gender="Male", City="Karad"},
new Employee(){ EmployeeId=4, Name="Ashwini", Gender="Female", City="Loha"}
};
TempData["employee"] = emp;
return View();
}
5. Remember to add using tempdatause.Models; otherwise getting error in Employee Controller.
6. Right-click on the action method and click on add view.
5.Please add two lines top of the view.
@using tempdatause.Models
@model IEnumerable<tempdatause.Models.Employee>
6.Add code in view.cshtml
<table class="table table-bordered">
<thead>
<tr>
<th> @Html.DisplayNameFor(e => e.EmployeeId)</th>
<th> @Html.DisplayNameFor(e => e.Name)</th>
<th> @Html.DisplayNameFor(e => e.Gender)</th>
<th> @Html.DisplayNameFor(e => e.City)</th>
</tr>
</thead>
<tbody>
@foreach (var Item in (IEnumerable<Employee>)TempData["employee"]) {
<tr>
<td>@Item.EmployeeId</td>
<td>@Item.Name</td>
<td>@Item.Gender</td>
<td>@Item.City</td>
</tr>
}
</tbody>
</table>
These steps are needed to follow for the store list and pass to view.
Limitations of TempData in MVC
1 Tempdata internally uses a session.
2.If the session was disabled then tempdata will not work.
3.In MVC TempData lifetime only for current and subsequent requests.
If you want to learn to create first unit test case please check here
ConversionConversion EmoticonEmoticon