Two Ways of Passing HTML5 Web Storage Data to ASP.NET

Introduction

HTML5 web storage allows you to store data on the client side. However, unlike cookies this data is not passed automatically to the server with every request-response cycle. To pass the data stored in web storage to the server you need to make some programmatic arrangement. Two ways by which such a data transfer can be facilitated are hidden form field and Ajax call. This article explains both of these techniques with an example. 

Overview of Web Storage

Traditionally ASP.NET developers used cookies to store small pieces of data on the client side. The data stored in cookies is passed to the server with every request and the cookies are sent from the server back to the client with every response. Thus, data stored in cookies is transferred to and from the server automatically. This automatic transfer of data is feasible because cookies allow you to store reasonably small amounts of data. HTML5 offers another way to store data on the client side - Web Storage. Web Storage comes in two flavors viz. localStorage and sessionStorage. The former type persists data on the machine across browser sessions whereas the later type of storage is discarded once a browser session ends. Both the types of web storage store data as key-value pairs. Like cookies you can't set a specific expiration date and time for the data stored in web storage.

Unlike cookies web storage allows you to store around 5 MB of data per origin. Although, web storage overcomes the storage limitation of cookies the stored data is not automatically transferred between client and server. This follows that you need to devise your own mechanism to facilitate such a data transfer. 

Two common techniques can be used to send data from the web storage to the server:

  • Sending data in a hidden field during a full page postback
  • Sending data via Ajax request

In the former technique you use a hidden form field. At the time of submitting the form you grab all the data from web storage and assign it to a hidden form field. You may use a variety of formats while storing web storage data into a hidden form field. Some of the possibilities include:

  • Comma separated values (CSV)
  • JSON object serialized as a string
  • XML

Which format you use depends entirely on your need and choice because it will be your custom code that is going to read this data. Since JSON is quite a popular format in web applications, storing data as a JSON string is a nice option. Another advantage of using JSON is that there are sophisticated libraries such as Json.NET to read this JSON data in the server side code and map it into a .NET object. If you use CSV or XML such a mapping would be your responsibility.

Now that you have some basic idea about web storage let's develop a simple application that will allow you to illustrate the concepts learned so far.

Storing Data in Web Storage

Before we discuss the data transfer techniques for web storage let's first develop a simple web form that saves some data to localStorage. The following figure shows how the web form looks:

Web Form
Web Form

As you can see, the web form consists of two textboxes for accepting Full Name and Email. There are three buttons that store data to localStorage, send it to the server via postback and send it to the server Ajax respectively. A Label below the buttons displays a success or error message during various operations.

Let's see the working of the first button - Save To Local Storage.

To store data to the localStorage you will use jQuery. So, make sure to add the jQuery library to your project and also add a <script> reference to it in the web form.

<script src="Scripts/jquery-2.0.0.js"></script>

Then add a <script> block and wire an event handler to the click event of the Save To Local Storage button. The complete code of the click event handler is shown below:

$(document).ready(function () {
  var storage = window.localStorage;
  $("#Button1").click(function(evt) {
    storage.setItem("fullname", $("#TextBox1").val());
    storage.setItem("email", $("#TextBox2").val());
    $("#Label3").html("Data saved to LocalStorage!");
    evt.preventDefault();
  });
});

As you can see, the first line of code declares a variable - storage - that holds a reference to window.localStorage object. This way you can use the variable as a shortcut to access the window.localStorage object. Additionally, you can easily switch and test your code for sessionStorage also.

The click event handler of Button1 stores two items in the localStorage - fullname and email. As discussed earlier localStorage stores data as key-value pairs. The setItem() method of localStorage allows you to add an item to the localStorage. The first parameter of the setItem() method is a key and the second parameter is a value. The value is retrieved from the textboxes. Once the fullname and email keys are stored in the localStorage a message is displayed in Label3 using the html() method of jQuery. Since you are using Button server control, calling evt.preventDefault() is necessary to avoid any form postback.

Passing Data from Web Storage to the Server Using Hidden Form Field

Now let's see how web storage data can be transmitted to the server using a full page postback and a hidden field. To do so you need to add a Hidden Field control of ASP.NET on the web form. Since this is a server control you can easily access its value after the postback. Also, install Json.NET in your project. You can install the Json.NET library by selecting PROJECT > Manage NuGet Packages and then search for Json.NET. The following dialog shows how Json.NET can be installed.

WebStorageWays - Manage NuGet Packages
WebStorageWays - Manage NuGet Packages

Once Json.NET is installed, add the following jQuery code in the <script> block you created earlier.

$("#Button2").click(function (evt) {
  var data = {};
  data.FullName = storage.getItem("fullname");
  data.Email = storage.getItem("email");
  $("#HiddenField1").val(JSON.stringify(data));
});

The above code shows the click event handler of the Send To Server via Postback button. The code defines a new JSON object and assigns two properties - FullName and Email. Notice how these properties are assigned from the data in the localStorage. The getItem() method accepts a key name and returns an item corresponding to that key. Once the JSON object is created it must be stored in the hidden form field. Since hidden form field can store data only as a string, JSON.stringify() method is used to convert the data JSON object to its string representation. Notice that in this case preventDefault() is not called because you want the post back to happen.

Next, add a class to the web application and name it UserData. The UserData class contains two properties, viz. FullName and Email and is shown below:

public class UserData
{
  public string FullName { get; set; }
  public string Email { get; set; }
}

The UserData class is a simple .NET class that stores FullName and Email. The client side data is to be mapped with the properties of UserData class so that you can work with it further in the system.

Now write the following code in the server side click event of Button2.

protected void Button2_Click(object sender, EventArgs e)
{
  string jsonData = HiddenField1.Value;
  UserData data = JsonConvert.DeserializeObject<UserData>(jsonData);
  Label3.Text = "Thank you " + data.FullName + "(" + data.Email + ")";
}

The above code retrieves the value of HiddenField1 in a string variable (jsonData). It then uses the DeserializeObject() method of the JsonConvert class to read the jsonData value and map it to an instance of UserData class. Remember that for this mapping to work correctly the client side property names and the server side property names must match. Once the data is mapped with UserData, a success message is displayed in Label3. The success message uses the FullName and Email properties of the UserData object to prove that the values are successfully received on the server.

You might be wondering as to why we used HiddenField in this example since Click event handler could have directly accessed the textbox values. While this is true in this example, consider a scenario where multiple web forms are storing values in the localStorage (say a wizard interface) and the final web form needs to send all the values to the server. In such cases you have to use a hidden form field to pass all the pieces of data from web storage to the server.

Passing Data from Web Storage to the Server Using Ajax

In the preceding technique you used full page postback to send data from the client to the server. You can also achieve the same results using Ajax. In the Ajax technique you use the jQuery $.ajax() method to call a server side resource and pass web storage data as a part of that Ajax call. The server side resource then uses the data as per your requirement. Ajax call can be made to web methods, web services, WCF services, MVC action methods or even to ASP.NET generic handlers (.ashx). In this example you will invoke a web method written in the code behind of the web form. The web method is shown below:

 [WebMethod]
public static string SaveData(UserData data)
{
  return "Thank you " + data.FullName + "(" + data.Email + ")";
}

As you can see the SaveData() web method accepts a parameter of type UserData. Inside, it simply creates a message string by concatenating UserData property values.

To call SaveData() web method from the client side add the following jQuery code in the <script> block.

$("#Button3").click(function (evt) {
  var data = {};
  data.FullName = storage.getItem("fullname");
  data.Email = storage.getItem("email");

  var options = {};
  options.url = "webform1.aspx/SaveData";
  options.type = "POST";
  options.data = JSON.stringify({ "data": data });
  options.dataType = "json";
  options.contentType = "application/json";
  options.success = function (result) { $("#Label3").html(result.d); };
  options.error = function (err) { $("#Label3").html("Error invoking the web method!"); };

  $.ajax(options);
  evt.preventDefault();
});

The above code represents the click event handler of Send To Server via Ajax button (Button3) and begins by creating a data JSON variable. As in the previous case, the data JSON object has two properties FullName and Email. The FullName and Email property values are assigned from localStorage.

Then, an options JSON object is created and its properties are assigned. The url property points to the SaveData() web method you wrote earlier. The type property indicates the HTTP method and is set to POST in this case. The data property indicates the data that is to be sent along the request. Notice that the data JSON object is further wrapped in a JSON object with data key. This key name (data) must be the same as the web method parameter name. JSON.stringify() method is used to convert the resultant JSON object into its string representation. The dataType and contentType properties indicate the data type of the response and request respectively. In this case they are set to json and application/json respectively. The success property is a callback function that is called when the remote call succeeds. In case there is any error, a function specified in the error property is called. The success function simply displays the string returned by the web method. The error function displays an error message in Label3. Finally, $.ajax() method of jQuery is used  to make the Ajax call

That's it! You can now run the web form and test whether data stored in the localStorage is successfully sent to the server using both of the techniques. 

Summary

HTML5 web storage offers a new way of storing data on the client. However, the data stored in web storage is not automatically passed to the server. This article examined two possible approaches for transferring data from web storage to the server. The first approach used postback and a hidden form field to pass the data to the server. The second approach involved an Ajax call to a web method for the sake of passing client side data.



Related Articles

Downloads

Comments

  • Passing WebStorage to Asp.net

    Posted by Shravan on 12/28/2013 02:33am

    Hi, This is very useful article for me. Thank you!

    Reply
  • Two Ways of Passing HTML5 Web Storage Data to ASP.NET

    Posted by Thomas Davenport on 12/05/2013 10:58pm

    A splendid article. The content is clearly explained and the example code works (not always the case). Well done. I look forward to more articles from Bipin Joshi

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

  • Live Event Date: April 22, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Database professionals — whether developers or DBAs — can often save valuable time by learning to get the most from their new or existing productivity tools. Whether you're responsible for managing database projects, performing database health checks and reporting, analyzing code, or measuring software engineering metrics, it's likely you're not taking advantage of some of the lesser-known features of Toad from Dell. Attend this live …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds