Passing Data From Controller To View Using Session - Part Five

This article will tell you almost everything about passing the data from Controller to View in ASP.NET MVC using session. I am writing this article to tell you the basic to advanced foremost concepts of the ways to pass data from Controller to View. This article is the fifth one in the series named “Passing Data from Controller to View”. You’ll learn all the ways in each separate article. Stay tuned!

I would strongly recommend reading my previous articles, which will be defining the basic concepts of ASP.NET MVC.

Especially, read my previous article in which I have taught the way of passing data from Controller to View using TempData. This is the link to the previous article. Read this article, check the code after downloading, and then feel free to give your feedback.

The topics to be covered are,

  1. What is Session?
  2. Passing the data from Controller to View using Session

Introduction and Background

As we know Controller is the class with a responsibility to handle all the HTTP requests and then execute appropriate View. On the other hand, View gives us the HTML markup that we display to the user. And for displaying anything on the View, there should be some data that is passed from Controller to View. And in this and next articles, you will learn how to pass data from Controller to View.

In this article, you’ll learn how to pass strongly typed data from Controller to View using Session. And you’ll see other ways to pass data, in coming articles. So stay tuned!

What is Session?

Session is a very famous and useful concept of web applications. It is used to pass the data from one page to another page. In the session object or session variable, you can put data and then use it where you want to display the data. A session variable is used to pass the data from Model to Controller or Controller to View. You’ll see, in this article, how to pass data from a Controller to View using the session variable.

A session is also one of the properties of “Controller” class so when we create a controller, that controller will automatically inherit the “Controller,” that’s why we can access this Session property in each controller. You can see the “Controller” class in below image in which the “session” property is defined.

Passing Data From Controller To View Using Session

This session object is also used to maintain the state across request and response. Because HTTP is stateless in nature, to maintain we use session object. This session object is used to hold information about the user and this information is available to all the pages of the application. Normally, we use a session to store user’s id, name or other preferences. This session is created by the server and then destroyed when the session expires.

Note
Only store small data into the sessions.

Now, the question is when does the session start and when does it end.

Passing the data from Controller to View using session

To pass the strongly typed data from Controller to View using session, we have to make a model class then populate its properties with some data and then pass that data to the session as Value. Selecting the Key’s name is the programmer’s choice. And then in the View, we can access the data of model class by using session with the pre-defined keys. Let’s create a project to take a look at an example.

Go to File >> New and select “Project” option.

Passing Data From Controller To View Using Session 

Then, create the ASP.NET web application project as depicted below.

Passing Data From Controller To View Using Session 

Then, select “Empty” and tick “MVC” followed by a click on OK.

Passing Data From Controller To View Using Session 

The project is created successfully.

Now, create a class named as “Employee” in the Models folder, as shown below.

Passing Data From Controller To View Using Session 
 
Passing Data From Controller To View Using Session 

Now, add some properties to this class using the code given below.

  1. namespace DataCtoV.Models  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         [Display(Name = "Serial No")]  
  6.         public byte EmployeeId { get; set; }  
  7.    
  8.         [Display(Name = "Name")]  
  9.         public string EmployeeName { get; set; }  
  10.    
  11.         public string Address { get; set; }  
  12.    
  13.         public string Phone { get; set; }  
  14.     }  
  15. }  

Now, we’ll add a controller from where this data of employee will pass. Let’s create a Controller.

Passing Data From Controller To View Using Session 

Then, select “MVC 5 Controller– Empty” then click Add.

Passing Data From Controller To View Using Session 

Give the name of the Controller and click on Add.

Passing Data From Controller To View Using Session 

The Controller is created successfully. In this Controller, we’ll make an action method with the name of “GetEmployeeData” in which we’ll make an object of “Employee” model class and populate this object with some data. Pass this object to the session with the help of a key named “employee”. The code of “EmployeeDataController” is given below.

  1. namespace DataCtoV.Controllers  
  2. {  
  3.     public class EmployeeDataController : Controller  
  4.     {  
  5.         // GET: EmployeeData  
  6.         public ActionResult GetEmployeeData()  
  7.         {  
  8.             List<Employee> emp = new List<Employee>  
  9.             {  
  10.                 new Employee  
  11.                 {  
  12.                     EmployeeId = 1,  
  13.                     EmployeeName = "John",  
  14.                     Address = "12 Fremont St. Clermont, FL 2813",  
  15.                     Phone = "+1-234-2838421"  
  16.                 },  
  17.                 new Employee  
  18.                 {  
  19.                     EmployeeId = 2,  
  20.                     EmployeeName = "Smith",  
  21.                     Address = "14 Highland Drive Fort Worth, TX 3994",  
  22.                     Phone = "+1-234-2244521"  
  23.                 },  
  24.                 new Employee  
  25.                 {  
  26.                     EmployeeId = 3,  
  27.                     EmployeeName = "Marry",  
  28.                     Address = "23 Fremont Road Milledgeville, GA 6788",  
  29.                     Phone = "+1-234-46568421"  
  30.                 }  
  31.             };  
  32.    
  33.         Session["employee"] = emp;  
  34.    
  35.             return View();  
  36.         }  
  37.     }  

We don’t have any View named as “GetEmployeeData” in the Views folder, so let’s create it. For creating a View, right click on the “GetEmployeeData” method and select “Add View…” option. The following dialogue box will open; click on “Add”.

Passing Data From Controller To View Using Session 

The View is created successfully. Let’s write the code for it.

  1. @using System.Collections  
  2. @using DataCtoV.Models  
  3. @model IEnumerable<DataCtoV.Models.Employee>  
  4. @{  
  5.     ViewBag.Title = "Employee Data";  
  6. }  
  7.    
  8. <h3>Employee Data</h3>  
  9.    
  10. <table class="table table-condensed table-hover">  
  11.     <thead>  
  12.         <tr>  
  13.             <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  14.             <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  15.             <th>@Html.DisplayNameFor(e => e.Address)</th>  
  16.             <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  17.         </tr>  
  18.     </thead>  
  19.     <tbody>  
  20.         @foreach (var employee in (IEnumerable<Employee>)Session["employee"])  
  21.         {  
  22.             <tr>  
  23.                 <td>@employee.EmployeeId</td>  
  24.                 <td>@employee.EmployeeName</td>  
  25.                 <td>@employee.Address</td>  
  26.                 <td>@employee.Phone</td>  
  27.             </tr>  
  28.         }  
  29.     </tbody>  
  30. </table>  

You can see in the code that we have made a table to represent the strongly typed data of the Employee model class. We have used foreach loop to iterate the data of each employee passed from the Controller.

To iterate the data, here we have used session which is calling the data from Controller with the help of key named as “employee”. And you can also see that we must have to cast the session to Employee.

Why casting?

Passing Data From Controller To View Using Session 

As we know, a session has type "object” and the foreach loop cannot accept variables having type “object”. In the object type, the GetEnumerator method is not defined that’s why we can’t iterate the data of Employee’s collection.

To iterate the data of Employee’s collection properly, we have to cast it to IEnumerable, because there a list/collection of Employees is coming and only in IEnumerable, the GetEnumerator is defined for iterating it properly. Hence we must have to cast it in the foreach loop. See the Error below without casting.

Passing Data From Controller To View Using Session 

Ways of Casting

One way of casting the session is described above, i.e., at the time of casting of a session in the foreach loop. The code is given below.

Passing Data From Controller To View Using Session 

Another way of casting the session is, cast the session in the Multi-Statement Razor Code block for C#, and then, use the variable in the foreach loop. You can see code below,

Casting in the code block.

  1. @{  
  2.    ViewBag.Title = "Employee Data";  
  3.    var employeeData = (IEnumerable<Employee>)Session["employee"];  }

Then, use the “employeeData” variable in the foreach loop, as shown below.

  1. @foreach (var employee in employeeData)  
  2.         {  
  3.             <tr>  
  4.                 <td>@employee.EmployeeId</td>  
  5.                 <td>@employee.EmployeeName</td>  
  6.                 <td>@employee.Address</td>  
  7.                 <td>@employee.Phone</td>  
  8.             </tr>  
  9.         }  

All the code of “GetEmployeeData” view is given below for your convenience.

  1. @using System.Collections  
  2. @using DataCtoV.Models  
  3. @model IEnumerable<DataCtoV.Models.Employee>  
  4. @{  
  5.     ViewBag.Title = "Employee Data";  
  6.     var employeeData = (IEnumerable<Employee>)Session["employee"];  
  7. }  
  8.    
  9. <h3>Employee Data</h3>  
  10.    
  11. <table class="table table-condensed table-hover">  
  12.     <thead>  
  13.         <tr>  
  14.             <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  15.             <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  16.             <th>@Html.DisplayNameFor(e => e.Address)</th>  
  17.             <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  18.         </tr>  
  19.     </thead>  
  20.     <tbody>  
  21.         @foreach (var employee in employeeData)  
  22.         {  
  23.             <tr>  
  24.                 <td>@employee.EmployeeId</td>  
  25.                 <td>@employee.EmployeeName</td>  
  26.                 <td>@employee.Address</td>  
  27.                 <td>@employee.Phone</td>  
  28.             </tr>  
  29.         }  
  30.     </tbody>  
  31. </table>  

 You have seen the reason for casting and the ways to do casting. Now simply let’s build and run the application. You should see the following output.

Passing Data From Controller To View Using Session 

Hence you have seen the practical example of a session. Now, let’s move towards its additional features.

Summary

In this article, you have learned how to pass strongly typed data from Controller to View using session, in which firstly, you should make a model class then populate its properties with some data then pass that object to the session as Value and pass magic Key as a string.

Conclusion

I hope this article has helped you in understanding the concepts about passing strongly typed data from Controller to View using session in ASP.NET MVC. Stay tuned for my next articles because this article is the fifth one in the series of “Passing data from Controller to View” and you’ll learn more about passing data in coming articles. If you have any query, please feel free to contact me in the comments section. Also, do provide the feedback whether positive or negative. It will help me to make my articles better and increase my enthusiasm to share my knowledge.