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,
- public ActionResult CheckRole(FormCollection frm)
- {
- string emailId = frm["EmailId"];
- string password = frm["Password"];
-
- if (emailId.ToLower() == "[email protected]" && password == "admin")
- {
- Session["username"] = emailId;
- return RedirectToAction("AdminHome", "Admin");
- }
- else if (emailId.ToLower() == "[email protected]" && password == "customer")
- {
- Session["username"] = emailId;
- return RedirectToAction("CustomerHome", "Customer");
- }
- return View("Login");
- }
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,
- <body>
- <nav class="navbar navbar-inverse navbar-fixed-top">
- <div class="container-fluid">
- <!-- Brand and toggle get grouped for better mobile display -->
- <div class="navbar-header">
- <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
- <span class="sr-only">Toggle navigation</span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- @Html.ActionLink("QuickKart", "Index", "Admin", null, new { @style = "font-size:24pt;color: aliceblue;", @class = "navbar-brand" })
- <ul class="nav navbar-nav" style="display:block;">
- @*<li><a href="index.html" style="font-size:24pt;color: aliceblue;">QuickKart</a></li>*@
- <li>@Html.ActionLink("View All Categories", "GetCategories", "Category", new { area = "" }, new { @class = "navbar-brand" })</li>
- <li>@Html.ActionLink("Add Category", "AddCategory", "Category", new { area = "" }, new { @class = "navbar-brand" })</li>
- <li>@Html.ActionLink("View All Offers", "GetOffers", "Offer", new { area = "" }, new { @class = "navbar-brand" })</li>
- <li>@Html.ActionLink("Add Offer", "AddOffer", "Offer", new { area = "" }, new { @class = "navbar-brand" })</li>
- </ul>
- </div>
- <!-- Collect the nav links, forms, and other content for toggling -->
- <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
- <ul class="nav navbar-nav navbar-right" style="margin-right:15px;">
- <li>@Html.ActionLink(" LogOut", "LogOut", "Home", new { area = "" }, new { @class = "navbar-brand glyphicon glyphicon-log-in", @style = "padding-top:10px;" }) </li>
- </ul>
- </div><!-- /.navbar-collapse -->
- </div><!-- /.container-fluid -->
- </nav>
- <h3 class="text-right">Hi @Session["username"].ToString().Split('@')[0] </h3>
- <div class="container-fluid">
- @RenderBody()
- <footer style="bottom:0;position:fixed;width:100%;text-align:center;">
- <p>copyright © @DateTime.Now.Year,QuickKart All Rights Reserved</p>
- </footer>
- </div>
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/bootstrap.min.js"></script>
- </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
- 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,
- <div class="col-md-6 col-sm-6 col-xs-6">
- @{
- if (Request.Browser.Cookies != false)
- {
- HttpCookie cookieObj = Request.Cookies["User"];
- if (cookieObj != null)
- {
- @Html.EditorFor(model => model.EmailId, new { htmlAttributes = new { @Value = cookieObj.Values[0] } });
- @Html.ValidationMessageFor(model => model.EmailId, "", new { @class = "text-danger" })
- }
- else
- {
- @Html.EditorFor(model => model.EmailId)
- <div>
- @Html.ValidationMessageFor(model => model.EmailId, "", new { @class = "text-danger" })
- </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
![]()