How to use session variable in MVC application
Session in MVC application
Session is very well known concept in any web application.
It is used to pass data from page to page. Basically web application is
stateless in nature. So, to maintain state across request and response we need
to use few technique, Session is one of them.
If you are web developer then you might know the concept of
session. In this article we will see how to use session variable in MVC web
application.
Using session variable we can pass data from model to
controller or controller to view. Here we will discuss with sample example. So,
Open a MVC3 application and go through below code.
Create a Model
Here we have created a sample Model called Customer. It has
only two fields.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVC3.Models
{
public class Customer
{
public String Name { get; set; }
public String Surname { get; set;
}
}
}
Create a Controller to process model data and set in session
variable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC3.Models;
namespace MVC3.Controllers
{
public class CustomerController : Controller
{
public ActionResult Index()
{
Customer Obj = new Customer();
Obj.Name = "Sourav ";
Obj.Surname = "Kayal";
Session["Customer"] = Obj;
return View();
}
}
}
Within controller we are creating object of model
class(Customer) and populating with data. Then we are inserting object of
customer class within session variable.
Create a view to display data
As we are using MVC3 application, we are allowed to create
Razor view. Lets create a razor view like below to access session data.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@{
var CustomerInfo = (MVC3.Models.Customer) Session["Customer"];
}
Customer Name is :- @CustomerInfo.Name;
<br />
Customer Surname is :-@CustomerInfo.Surname;
</div>
</body>
</html>
Here is view for aspx view engine.
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<dynamic>"
%>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
<% var Customer = (MVC3.Models.Customer)Session["Customer"]; %>
Customer Name is :- <%= Customer.Name %><br />
Cstomer Surname is :- <%= Customer.Surname %>
</div>
</body>
</html>
Output:

Conclusion:-
Here we have learned how to pass session data in MVC application. You can use session variable to pass from Controller to model