How To Do State Management In ASP.NET MVC

Introduction

As we all know, HTTP is a stateless protocol, i.e., each HTTP request does not know about the previous request. If you are redirecting from one page to another page, then you have to maintain or persist your data so that you can access it further. To do this, there were many techniques available in ASP.NET like ViewState, SessionState, ApplicationState etc.

 

State management techniques are another feature of ASP.NET MVC that may assist us in maintaining the data when switching from one page to another or staying on the same page after a reload. In ASP.NET MVC, there are a number of options, which are as follows.

  1. Hidden Field
  2. Cookies
  3. Query String
  4. ViewData
  5. ViewBag
  6. TempData

 

When switching from “Controller” to “View” or “Controller” to “Controller,” the aforementioned objects assist us in persisting our data on the same page. Let’s put these into practice right now so that we can better grasp.

Hidden Field

Since HTML programming taught us about it, it is not new. Your client-side data can be hidden using a hidden field. Although the user cannot see it immediately on the UI, the value is visible in the page source. Therefore, if you wish to store sensitive data, you should avoid doing this. It merely serves to store a tiny amount of frequently updated data.

The employee’s ID is stored in the code below with the value 1001.

 

@Html.HiddenFor(x=>x.Id)

The following line of code, which is simply the HTML version of the aforementioned code with value, may be found if you open the page source code for that page in your browser. Just concentrate on the latter three qualities.

 

<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="1001" />

 

Cookies

Cookies are used to store data, although the amount of data stored should be minimal. We can store our data in it in the same way as a simple text file. The creation of a cookie in client side memory by the browser is advantageous. After logging in, we frequently utilize a cookie that has an expiration date to store user information. In essence, the server generates a cookie and responds by sending it to the browser. It is kept in client-side memory by the browser.

In ASP.NET MVC, cookies can also be used to maintain data for requests and responses. It might look like the code below.

 

HttpCookie cookie = new HttpCookie("TestCookie");  
cookie.Value = "This is test cookie";  
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);

Here, we’ve made a single cookie with the name “TestCookie.” Multiple cookies can be made and added with Response. Prior to accessing the value stored in an existing cookie, we must first determine whether the cookie is available or not.

if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("TestCookie"))  
{  
  HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["TestCookie"];    
  ViewBag.CookieMessage = cookie.Value;  
}

 

All cookies have an expiration date. You can generate a cookie in a controller’s action method, save it on the client side, and then simply access it in another action method.

Query String

A query string is typically used in ASP.NET to transmit values from one page to the next. The same is possible with ASP.NET MVC.

http://localhost:49985/home/editemployee?name=TestValue

With the URL shown above, I’m making one request. As you can see in the following image, I am giving the name’s value as a query string and it will be accessible on the “EditEmployee” action method in the “Home” controller.

ViewData

When we send data from the Controller to the View, it aids in the maintenance of your data. It is an object that derives from ViewDataDictionary and is a dictionary. It accepts the information in a key-value pair because it is a dictionary object.

The value will become null when you build a ViewData object, pass the data, then perform a redirection. ViewData’s data is no longer valid for pending requests. When using ViewData, be sure to check for null and typecasting for complicated data types, respectively.

 

public ActionResult Index()  
{  
     Employee emp = new Employee()  
     {  
         Id = 1001,  
         Name = "Mukesh Kumar",  
         Address = "New Delhi",  
         Age = 25  
     };  
              
     ViewData["Message"] = "This is ViewData";  
     ViewData["Emp"] = emp;  
  
     return View();  
}

 

Two ViewData dictionary objects—ViewData[“Message”] and ViewData[“Emp”]—can be found in the code above. The first is a straightforward string value, but the second has intricate employee data. Prior to rendering the view, we must first determine whether the ViewData is null; if it is not, we may then obtain the value.

 

@{  
    ViewBag.Title = "Home Page";  
}  
  
<div class="row">  
    <div class="col-md-4">  
        <h2>Employee Details</h2>  
        <br />  
        <p>  
            @if(ViewData["Message"] !=null)  
            {  
                <b>@ViewData["Message"].ToString();</b>  
            }  
        </p>  
        <br />  
        @if (ViewData["Emp"] != null)  
        {  
  
            var emp = (MVCStateManagement.Models.Employee)ViewData["Emp"];  
            <table>  
                <tr>  
                    <td>  
                        Name :  
                    </td>  
                    <td>  
                        @emp.Name  
                    </td>  
                </tr>  
                <tr>  
                    <td>  
                        Address :  
                    </td>  
                    <td>  
                        @emp.Address  
                    </td>  
                </tr>  
                <tr>  
                    <td>  
                        Age :  
                    </td>  
                    <td>  
                        @emp.Age  
                    </td>  
                </tr>  
            </table>              
        }  
    </div>  
</div>

ViewBag

The duties of ViewData and ViewBag are identical. The data is also transferred from Controller to View using it. The main distinction is that ViewBag is an object with the Dynamic property, which was added in C# 4.a. It functions as a wrapper for ViewData. Using ViewBag instead of ViewData will eliminate the necessity for typecasting complex objects and the need to check for null.

The output will be the same if we use ViewBag with the same code as above.

public ActionResult Index()  
{  
    Employee emp = new Employee()  
    {  
        Id = 1001,  
        Name = "Mukesh Kumar",  
        Address = "New Delhi",  
        Age = 25  
    };  
              
    ViewBag.Message = "This is ViewBag";  
    ViewBag.Emp = emp;  
  
    return View();  
}

 

You must use ViewBag to modify ViewData on the View.

@{  
    ViewBag.Title = "Home Page";  
}  
  
<div class="row">  
    <div class="col-md-4">  
        <h2>Employee Details</h2>  
        <br />  
        <p>  
  
            <b>@ViewBag.Message</b>  
  
        </p>  
        <br />  
        @{  
            var emp = ViewBag.Emp;  
            <table>  
                <tr>  
                    <td>  
                        Name :  
                    </td>  
                    <td>  
                        @emp.Name  
                    </td>  
                </tr>  
                <tr>  
                    <td>  
                        Address :  
                    </td>  
                    <td>  
                        @emp.Address  
                    </td>  
                </tr>  
                <tr>  
                    <td>  
                        Age :  
                    </td>  
                    <td>  
                        @emp.Age  
                    </td>  
                </tr>  
            </table>  
        }  
    </div>  
</div>

 

 

Note

It will produce an error if you use ViewData that is not defined on the Controller; if you use ViewBag, it won’t.

Use different names for ViewBag and ViewData; otherwise, only one message will appear. The controller’s code below uses ViewData and ViewBag objects with the same name, “Message.”

 

public ActionResult Index()  
{  
     ViewData["Message"] = "This is ViewData";  
     ViewBag.Message = "This is ViewBag";              
  
     return View();  
}

 

On view defined both as following.

<b>@ViewBag.Message</b>  
@if(ViewData["Message"]!=null)  
{  
      ViewData["Message"].ToString();  
}

 

The final message—in this case, “This is ViewBag”—will be the only one to appear in the output.

TempData

 

Like ViewData, TempData is a dictionary object that holds data as a key/value pair. From TempDataDictionary, it is derived. It primarily functions as a means of data transmission from one request to the next, or the succeeding request. The TempData data will be cleaned if it has already been read. There are various methods for persisting the data. Everything hinges on how you interpret the evidence.

Data Not Read

Your data is accessible with the next request if you haven’t read it during the redirection procedure. You can see that we created a TempData[“Emp”” in the following code, but neither an action method nor a view read it.

Therefore, the TempData[“Emp”] will be available after the “About” page renders and if we switch to the “Contact” page.

Note

Do not read data on View.

public ActionResult Index() 
{
 Employee emp = new Employee() {
  Id = 1001, Name = "Mukesh Kumar", Address = "New Delhi", Age = 25
 };

 //Setting the TempData  
 TempData["Emp"] = emp;
 return RedirectToAction("Index1");
}

public ActionResult Index1()
{
 //Not reading TempData  
 return RedirectToAction("Index2");
}

public ActionResult Index2()
{
 //Not reading TempData  
 return RedirectToAction("About");
}

public ActionResult About()
{
 //Not reading TempData  
 return View();
}

public ActionResult Contact()
{
 //Data will available here because we have not read data yet  
 var tempEmpData = TempData["Emp"];
 return View();
}

 

 

Standard Data Read

If you try to access the value on the “Contact” page after reading the information on the “About” page as it renders, it won’t be there.

@{  
    ViewBag.Title = "About";  
}  
<h2>About Page</h2>  
<br />  
@{   
    var data = (MVCStateManagement.Models.Employee)TempData["Emp"];  
}

Since we previously read the information on the “About” page, TempData won’t be available on the Contact page. If you haven’t read yet, TempData is only accessible with a future request.

public ActionResult Contact()
{
 //Data will not available here because already read on About page  
 var tempEmpData = TempData["Emp"];
 return View();
}

Keep TempData

After reading the information on the “About” page, you can use the “Keep()” method if you still want to keep the data for the subsequent request. Your data will be stored for the following request if you use the Keep method.

@{   
    var data = (MVCStateManagement.Models.Employee)TempData["Emp"];  
    TempData.Keep();  
}

 

The contact page will display TempData because we are using the Keep() function to preserve the data.

public ActionResult Contact()  
{  
      //TempData will available here because we have keep on about page  
      var tempEmpData = TempData["Emp"];  
      return View();  
}  

 

Peek TempData

We may immediately get the TempData value and store it for the upcoming requests by using the Peek() method.

@{   
    var data = (MVCStateManagement.Models.Employee)TempData.Peek("Emp");      
} 

The Temporary Data will be accessible once we switch to the “Contact” page.

public ActionResult Contact()
{
 //TempData will available because we have already keep data using Peek() method.  
 var tempEmpData = TempData["Emp"];
 return View();
}

 

Conclusion

We have learned state management strategies today to aid with data maintenance.

 

I hope you find this post useful. Please give me your opinion so I can make the following entries better. Please post your questions in the comments area if you have any.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories