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 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 define 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 a 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. In this and the 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 a Session?

The 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 the Model to the Controller or Controller to View. You’ll see, in this article, how to pass data from a Controller to a View using the session variable.

A session is also one of the properties of the “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 the below image in which the “session” property is defined.

Session

This session object is also used to maintain the state across request and response. Because HTTP is stateless, to maintain we use session objects. 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 the 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 in the sessions.

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

Passing the data from the controller to view using the session

To pass the strongly typed data from Controller to View using session, we have to make a model class 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 the model class by using a session with the pre-defined keys. Let’s create a project to take a look at an example.

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

File

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

Visual c sharp

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

Empty

The project is created successfully

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

Class

Employee

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

namespace DataCtoV.Models
{
    public class Employee
    {
        [Display(Name = "Serial No")]
        public byte EmployeeId { get; set; }
        [Display(Name = "Name")]
        public string EmployeeName { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
    }
}

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

Controller

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

MVC five

Give the name of the Controller and click on Add.

Add

The Controller is created successfully. In this Controller, we’ll make an action method with the name “GetEmployeeData” in which we’ll make an object of the “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.

namespace DataCtoV.Controllers
{
    public class EmployeeDataController : Controller
    {
        // GET: EmployeeData
        public ActionResult GetEmployeeData()
        {
            List<Employee> emp = new List<Employee>
            {
                new Employee
                {
                    EmployeeId = 1,
                    EmployeeName = "John",
                    Address = "12 Fremont St. Clermont, FL 2813",
                    Phone = "+1-234-2838421"
                },
                new Employee
                {
                    EmployeeId = 2,
                    EmployeeName = "Smith",
                    Address = "14 Highland Drive Fort Worth, TX 3994",
                    Phone = "+1-234-2244521"
                },
                new Employee
                {
                    EmployeeId = 3,
                    EmployeeName = "Marry",
                    Address = "23 Fremont Road Milledgeville, GA 6788",
                    Phone = "+1-234-46568421"
                }
            };

            Session["employee"] = emp;

            return View();
        }
    }
}

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

Get employee

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

@using System.Collections
@using DataCtoV.Models
@model IEnumerable<DataCtoV.Models.Employee>
@{
    ViewBag.Title = "Employee Data";
}
<h3>Employee Data</h3>
<table class="table table-condensed table-hover">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>
            <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>
            <th>@Html.DisplayNameFor(e => e.Address)</th>
            <th>@Html.DisplayNameFor(e => e.Phone)</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var employee in (IEnumerable<Employee>)Session["employee"])
        {
            <tr>
                <td>@employee.EmployeeId</td>
                <td>@employee.EmployeeName</td>
                <td>@employee.Address</td>
                <td>@employee.Phone</td>
            </tr>
        }
    </tbody>
</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 a foreach loop to iterate the data of each employee passed from the Controller.

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

Why casting?

Why casting

As we know, a session has the type "object” and the theforeach loop cannot accept variables having the type “object”. In the object type, the theGetEnumerator 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 cast it in the theforeach loop. See the Error below without casting.

Error below

Ways of Casting

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

Ways of casting

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

Casting in the code block.

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

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

@foreach (var employee in employeeData)
{
    <tr>
        <td>@employee.EmployeeId</td>
        <td>@employee.EmployeeName</td>
        <td>@employee.Address</td>
        <td>@employee.Phone</td>
    </tr>
}

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

@using System.Collections
@using DataCtoV.Models
@model IEnumerable<DataCtoV.Models.Employee>
@{
    ViewBag.Title = "Employee Data";
    var employeeData = (IEnumerable<Employee>)Session["employee"];
}
<h3>Employee Data</h3>
<table class="table table-condensed table-hover">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>
            <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>
            <th>@Html.DisplayNameFor(e => e.Address)</th>
            <th>@Html.DisplayNameFor(e => e.Phone)</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var employee in employeeData)
        {
            <tr>
                <td>@employee.EmployeeId</td>
                <td>@employee.EmployeeName</td>
                <td>@employee.Address</td>
                <td>@employee.Phone</td>
            </tr>
        }
    </tbody>
</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.

Employee data

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

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 populate its properties with some data 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 a 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 queries, please feel free to contact me in the comments section. Also, do provide feedback whether positive or negative. It will help me to make my articles better and increase my enthusiasm to share my knowledge.


Similar Articles