HTTP is a stateless protocol; this protocol cannot store user information on the server-side as per user basis because Web server treats each HTTP request for a page as an independent request. No server has knowledge of any kind of variable value. ASP.NET MVC Session state enables you to store and retrieve values for a user when the user navigates another view in an ASP.NET MVC application. The session is defined as the period of time that a unique user interacts with a Web application.
In this article, I tell you how to pass data from one view to another in ASP.NET MVC using session and also I tell you how to manage login user information using session. Steps are given below
Step 1: First create a model class and some properties as below
namespace SessionAspDotNetMvc.Models
{
/// <summary>
/// Class with three properties
/// </summary>
public class SessionAspDotNetMvcModel
{
// property for set user's id
public string sUserID
{
get;
set;
}
// property for set user's password
public string sPassword
{
get;
set;
}
// property for set session value
public string sSessionValue
{
get;
set;
}
}
}
Step 2: Create two actions within the controller (e.g. Home controller) as below
using System;
using System.Web.Mvc;
// Added model namespace
using SessionAspDotNetMvc.Models;
namespace SessionAspDotNetMvc.Controllers
{
public class HomeController : Controller
{
///<summary>
/// Default action name
///</summary>
///<returns></returns>
public ActionResult Index()
{
return View();
}
///<summary>
/// Second action where we receive session value
///</summary>
///<param name="data"></param>
///<returns></returns>
[HttpPost]
public ActionResult Index(SessionAspDotNetMvcModel data)
{
// Assign value into session
Session["SessionUserID"] = data.sUserID;
// Redirect view
return RedirectToAction("EmployeeSection");
}
public ActionResult EmployeeSection()
{
// Create object of model call for call properties and set value
var vSessionValue = new SessionAspDotNetMvcModel();
try
{
// check existing value into session
if ((Object)Session["SessionUserID"] != null)
// assign value into properties
vSessionValue.sSessionValue = "Welcome " +
Session["SessionUserID"].ToString();
else
// if session expired than set custom message
vSessionValue.sSessionValue = "Session Expired";
}
catch
{
}
// return value to view
return View(vSessionValue);
}
}
}
Step 3: Write the line of code for index view as below
@model SessionAspDotNetMvc.Models.SessionAspDotNetMvcModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div style="width: 100%; height: 100px; background-color: LightBlue;">
</div>
<div style="width: 100%; height: 315px;">
<fieldset style="width: 250px; margin-left: 500px; margin-top:100px;">
<legend>Login </legend>
@using (Html.BeginForm())
{
<table>
<tr>
<td align="right";>
User ID:
</td>
<td>
@Html.TextBoxFor(m => m.sUserID)
</td>
</tr>
<tr>
<td align="right";>
Password:
</td>
<td>
@Html.PasswordFor(m => m.sPassword)
</td>
</tr>
<tr>
<td>
</td>
<td align="right";>
<input id="btnLogin" type="submit" value="Login" />
</td>
</tr>
</table>
}
</fieldset>
</div>
<div style="width: 100%; height: 100px; background-color: LightBlue;">
</div>
</body>
</html>
Write a line of code for EmployeeSection view as below
@model SessionAspDotNetMvc.Models.SessionAspDotNetMvcModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>EmployeeSection</title>
</head>
<body>
<div style="width: 100%; height: 100px; background-color: LightBlue;">
</div>
<div style="width: 100%; height: 315px;">
<h4>
@Html.DisplayFor(m => m.sSessionValue) </h4>
</div>
<div style="width: 100%; height: 100px; background-color: LightBlue;">
</div>
</body>
</html>
Step 4: Set session expired time value on web.config page as below
<system.web>
<sessionState mode="InProc" timeout="5" />
</system.web>
Note: Here timeout="5”, indicate session expired time is 5 minutes. If we do not specify session time out value than session default expired time is 20 minutes.
Step 5: if you want to do something after session expired then write a line of code within the Session_End method in Global.asax.cs as below
/// <summary>
/// This method execute when session time expired
/// </summary>
protected void Session_End()
{
// do somthing here
}
Step 6: Build and Save application and press F5 for execution and see screenshot as below image
Note: Here this is a simple demo, so I’m not checking any authentication for login. I’m simple store user id into session and pass to another view (e.g. EmployeeSection). When you click on the Login button and see EmployeeSection view UI as below image
Step 7: Wait for 5 minutes, if you do not refresh the page within 5 minutes (in this demo) then after 5 minutes session expired and when next time you refresh the page, session expired message display as below image.
Note: Session expires time to start to count, when you did not do anything after login.
Anonymous User
27-Jun-2019Thanks, Sir, It is a very helpful article.
Anonymous User
29-Jan-2019It was very informative.
Andrew Tappert
10-Aug-2016