State Management In MVC

Introduction

 
In this article we are going to discuss state management techniques in MVC.
 
Collection of input values (eg. e-mail id, city, mobile number etc..) of a particular web page is known as state of that page. By default web applications can not retain the values (state) provided in one page, when you navigate to another page. This nature is called stateless behavior.
 
You can use state management techniques to retain the values (state) across the pages. ASP.NET MVC supports the following common state management techniques,
  • Session
  • Query string
  • Cookies
Cookies and query string variables are stored on client/browser memory, where as session variables are stored on server memory. You will learn these state management techniques in the following demos.
 

Demosteps

 
In order to understand state management in MVC using session, try out the following demo steps,
 
Session is structured as a key/value dictionary for storing information that needs to be maintained between server round trips and between requests for pages.Session objects are stored in the server. 
 
As per the requirement, the username of the admin should be displayed across all his pages. This can be achieved by using Session variable. 
 
Step 1
 
Go to File -> Open -> Project/Solution. 
 
Step 2
 
Add the code as given below in CheckRole action of HomeController to store the username of admin as well as Customer in session,
  1. public ActionResult CheckRole(FormCollection frm)  
  2.        {  
  3.            string emailId = frm["EmailId"];  
  4.            string password = frm["Password"];  
  5.   
  6.            if (emailId.ToLower() == "admin@gmail.com" && password == "admin")  
  7.            {  
  8.                Session["username"] = emailId;  
  9.                return RedirectToAction("AdminHome""Admin");  
  10.            }  
  11.            else if (emailId.ToLower() == "customer@gmail.com" && password == "customer")  
  12.            {  
  13.                Session["username"] = emailId;  
  14.                return RedirectToAction("CustomerHome""Customer");  
  15.            }  
  16.            return View("Login");  
  17.        }  
Step 3
 
To fetch the username for admin from session object and display across all the pages, add the code given below in _LayoutAdmin.cshtml as shown,
  1. <body>  
  2.     <nav class="navbar navbar-inverse navbar-fixed-top">  
  3.         <div class="container-fluid">  
  4.             <!-- Brand and toggle get grouped for better mobile display -->  
  5.             <div class="navbar-header">  
  6.                 <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">  
  7.                     <span class="sr-only">Toggle navigation</span>  
  8.                     <span class="icon-bar"></span>  
  9.                     <span class="icon-bar"></span>  
  10.                     <span class="icon-bar"></span>  
  11.                 </button>  
  12.                 @Html.ActionLink("QuickKart""Index""Admin"nullnew { @style = "font-size:24pt;color: aliceblue;", @class = "navbar-brand" })  
  13.                 <ul class="nav navbar-nav" style="display:block;">  
  14.                     @*<li><a href="index.html" style="font-size:24pt;color: aliceblue;">QuickKart</a></li>*@  
  15.                     <li>@Html.ActionLink("View All Categories""GetCategories""Category"new { area = "" }, new { @class = "navbar-brand" })</li>  
  16.                     <li>@Html.ActionLink("Add Category""AddCategory""Category"new { area = "" }, new { @class = "navbar-brand" })</li>  
  17.                     <li>@Html.ActionLink("View All Offers""GetOffers""Offer"new { area = "" }, new { @class = "navbar-brand" })</li>  
  18.                     <li>@Html.ActionLink("Add Offer""AddOffer""Offer"new { area = "" }, new { @class = "navbar-brand" })</li>  
  19.                 </ul>  
  20.             </div>  
  21.             <!-- Collect the nav links, forms, and other content for toggling -->  
  22.             <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">  
  23.                 <ul class="nav navbar-nav navbar-right" style="margin-right:15px;">  
  24.                     <li>@Html.ActionLink(" LogOut""LogOut""Home"new { area = "" }, new { @class = "navbar-brand glyphicon glyphicon-log-in", @style = "padding-top:10px;" }) </li>  
  25.                 </ul>  
  26.             </div><!-- /.navbar-collapse -->  
  27.         </div><!-- /.container-fluid -->  
  28.     </nav>  
  29.     <h3 class="text-right">Hi @Session["username"].ToString().Split('@')[0]   </h3>  
  30.     <div class="container-fluid">  
  31.         @RenderBody()  
  32.         <footer style="bottom:0;position:fixed;width:100%;text-align:center;">  
  33.             <p>copyright © @DateTime.Now.Year,QuickKart  All Rights Reserved</p>  
  34.         </footer>  
  35.     </div>  
  36.     <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  37.     <script src="~/Scripts/bootstrap.min.js"></script>  
  38. </body>  
Step 4
 
Similarly add the above line in _LayoutCustomer.cshtml to fetch the username for Customer from session object and display across all the pages.
 
Step 5
 
Build and run the application. Login as admin and observe the admin homepage. 
 
Observe that the user name is visible on the Admin home page. The username will also be visible across all the pages accessible to Admin. Similarly you can try this for customer. 
 
Querystring
  • QueryString is a client side state management technique used to pass the information by appending it to the end of the page URL as key value pairs. 
  • A query string can be used to submit data back to your page or to another page through the URL.
  • It provides a simple but limited way to maintain some state information.For example, query string are an easy way to pass information from one page to another, such as passing a product number to another page where it will be processed. However it is not good to send sensitive information like password through query string.
  • To pass more than one value via Query String, ?, & can be used as shown : ControllerName/ActionName?Variable1=Value1&Variable2=Value2
  1. return Redirect("/Support/Questions?QuestionType=" + QuestionCategory[0]);  
Here, the Questionype after ? is the key and the value for it is specified after =.
 
Cookies
  • You have to store the user credentials in the client machine so that it is auto populated the next time the user logs in, you will make use of the cookie. 
  • Cookies are useful in storing small amounts of information on the client. The information is sent with the request to the server. It is lightweight, text-based structure with simple key-value pairs.
  • Ex : We add checkbox which will be used to check for storing the login credentials on the client machine for further use.
  • It stores the login credentials in the form of key-value pair. Keys for the User cookie are 'UserId' and 'Password' and corresponding values are taken from the login page using FormCollection object.
  • To define the lifetime of the cookie to be stored on the client side you can make use of Expires property as shown in the code. Here you have set the expiration time as 1 day.
  • Response.Cookies.Add() - this method is used to add the cookie to the client machine.
  • In certain browsers, cookies might be disabled. In order to check if cookie storage is enabled in your browser, you can use Request.Browser.Cookies. It returns true if the cookie storage is enabled in your browser.
  • When the login page is requested, the presence of the cookie is checked on the client machine using Request.Cookies. If there is a cookie present in the n given name, then the values are retrieved using CookieObject.Values (here cookieObj.Values).Since UserId is stored in index position 0, it is retrieved and displayed in the User Name text box. If the cookie is not present, the text box will be empty.
Similarly, you can populate the password textbox from cookie object as below,
  1. <div class="col-md-6 col-sm-6 col-xs-6">  
  2.                                @{  
  3.                                    if (Request.Browser.Cookies != false)  
  4.                                    {  
  5.                                        HttpCookie cookieObj = Request.Cookies["User"];  
  6.                                        if (cookieObj != null)  
  7.                                        {  
  8.                                            @Html.EditorFor(model => model.EmailId, new { htmlAttributes = new { @Value = cookieObj.Values[0] } });  
  9.                                            @Html.ValidationMessageFor(model => model.EmailId, ""new { @class = "text-danger" })  
  10.                                        }  
  11.                                        else  
  12.                                        {  
  13.                                            @Html.EditorFor(model => model.EmailId)  
  14.                                            <div>  
  15.                                                @Html.ValidationMessageFor(model => model.EmailId, ""new { @class = "text-danger" })  
  16.                                            </div>  
In the putput window, observe that the credentials are auto filled from the cookie object.
 
As you have noticed session state is stored in server memory and query string /cookies are stored in client/browser memory. Depending on where the 'state' is stored, the management techniques are known as server side or client side.
 
Session (Server side state management technique),
  • Allows you to set and read values specific to user as the user navigates between pages in a web application .
  • By default these state variables are stored in main memory of host application, it can also be configured to store on SQL server database.
  • A session variable can be removed from memory using Session.Clear() method.
Query string (Client side state management technique),
  • Simple technique to store values along with url 
  • Cannot store composite type values
  • Should not be used for confidential data like passwords, as query string area visible as part of url.
Cookies (Client side state management technique),
  • Stores data in browsers memory 
  • Some browsers may not accept cookies based on settings

Summary

 
In this article, we have explored the concept of State Management in MVC where we have gone through the server side and client side state management technique with the help of Session, Cookie, Querystring. Hope you like the article. Until next time - Happy Learning Cheers