Share via


How to share data among different web pages using ASP.NET

Introduction

The data sent to the server is of utmost importance and must be accessible by all of the methods that require the data, usually when the UI of the website is improtant for the developers. Sending the data from the website’s one page, to another page where the actual business logic layer is going to take action might be hard for you, or maybe you might also want to first store those data values into your server and perform tasks on it like saving it, and then you might delete the data from the server after it have been consumed.

ASP.NET exposes different tasks, that you might use, some of these methods are inherited from default HTML methods to share the data, whereas a few of these are standards defined and then consumed by ASP.NET to let the developers share the same data throughout the web pages who need the data from the user instead of creating a database to store them in.

Sharing the Data

Sharing the data in ASP.NET is as simple as 1, 2, 3. Well, not really it really does require some coding by you and you might need to first gain some understanding of these features before you can implement them in your own projects. For example, the form method of sending the data to other web pages, can be as semantic as it can be. But there are a few objects in ASP.NET that you might consider learning before you can actually work with it.

I will go through a few of them in this blog post, and I hope you can understand the concept behind them. The example I will add to the sections would be easy one and understandable one, I will include the comments to it too and I will also link the documentation that might help you to learn more on these sections and technologies too. The techniques used are never best, because only thing that matters is the data that is to be sent. You can use any method that you’ve already excel in and it will send the data, no need to focus on just one task. You must always look for the most efficient method for everything.

Using a form

The first and the most simplest method to send the data from one page to other web page is to use a simple HTML form, to get the data from the user, and then pass it on to the next page using action attribute. This way, you can get the data on one web page, perform some tasks on the data on second web page where your business logic layer is situated and then continue to the next page to show the results or come back to the same page.

Let us, take a daily life example, suppose you were to create a simple web page that would ask the users for their name and if their name matches the condition (their name is the name you wanted them to write) then you can allow them to do some task, otherwise show them any other message or what so ever you might do then. In the ASP.NET form, it would be as the following HTML form,

<p>Please enter your name below:</p>
<form method="post" action="secondpage.cshtml">
   <input type="text" name="name" />
   <input type="submit" value="Submit" />
</form>

The above code, when will render, will be a simple form with one input button and a button. That was the default HTML behaviour, now let us take a look at code that ASP.NET will work on, it is like this,

if(IsPost) { // IsPost is available in Web Pages framework System.Web.WebPages.dll
    // The request is Post, data was shared to this page, 
    // get the value for the 'name' input field
    var name = Request["name"]; 
    if(name == "Secret-Name") {
        // yes the name was correct, 
    }
    Response.Redirect("~/first-page.cshtml");
}

Yes, I have not included an else block, but you know you can define a specific condition to state the state of your choice. You can add a new queryString to the string passed to the Response.Redirect function to indicate a change on other page and so on. Like this,

Response.Redirect("~/first-page?response=done");

Then inside the page, you can ge this value to show that the process was completed like this,

@if(Request.QueryString["response"] == "done") {
    <p>The process requested has completed successfully.</p>
}

The name, from one page, was shared to another page where the actual business logic was present! It is a good approach, and recommended way to split your code into sections and never write the business logic layer into the GUI. Always call a method to perform tasks.

Session variables

Second efficient way of doing the same trick is by using the session variables. Good thing about them, is that they’re deleted as soon as the session expires. Another plus point for them is that you can always clear them out programmatically. You can create session variables, as much as you want and you don’t have to stick to any naming convention. You can name them as you want and they will be available to you inside the website on every page throughout the session.

Let us use the same above example, and try to dig deeper and look how can we complete the above mentioned scenario using a session variable methodology. We will continue, from the stage where the user has clicked on the Submit button. The ASP.NET code for this would be like this,

// on the same page, you use can use Request.Form["key"];
var name = Request.Form["name"];
// now just pass this value, to a new Session variable
Session["name"] = name;
// done! Now this value is available through the website.

Important thing to note here is that you can name the variable as you want it to. If that name is already present inside the collection, it will be modified (overwritten) otherwise, it will be created. Now, on the second page, you can change the code and write this page instead,

if(Session["name"] != null) {
   // if that value is present
   var name = Session["name"].ToString();
   if(name == "Secret-Name") {
      // name matches
   }
   Response.Redirect("~/first-page.cshtml");
}

Another interesting thing here to note is, that since these variables can be cleared easily it is important to use an if else block to check for their existence or value. Session variable can be cleared by OS, by Browser, by User (if he clears the session by closing the browser) or by the code-behind. There are different methods to clear the data yourself, if there is an error in conditions etc. The following list shows these methods,

  1. Session.Abandon()
    Cancels the current session.
  2. Session.Clear()
    Clears the session.
  3. Session.RemoveAll()
    Similar to the above method, Session.Clear().

To totally clear the session, to terminate it, it is usually a good approach to call the Session.Abandon() method. Which will wipe out the session as whole.

Good thing about these Session variables is that you can store any kind of data in them. From built-in data type like string, character, integer like data types to custom classes. Only thing to consider is to change the data to their specific format (data type) before using them by casting them, to their own type, such as this code,

class Example {
   public string  Name { get; set; }
   public int  Age { get; set; }
}
 
Example example = new  Example();
example.Name = Request.Form["name"];
// Convert them to Int type, because of data type of 'Age'
example.Age = Convert.ToInt16(Request.Form["age"]);
// Save the object
Session["object"] = example;
Now, you can extract this  object like this,
 
// Cast it
Example example = (Example)Session["object"];

Make sure that you’ve used the if else block to avoid the NullReferenceException being thrown.

Cookies are a good way to store the data, that can be used later through different other calls from the website. They’re stored on the client’s machine and a copy of the data is used by the website to determine who the user is, what he wants and what he might expect from us. To perform the same above task in an HttpCookie way, you would write the code as this one (we will again start once the user has clicked the button),

var cookie = new  HttpCookie("form-data"); // create the Cookie instance, 
cookie["name"] = Request.Form["name"]; // pass the data
// Add the cookie to response, to send it to the client
Response.Cookies.Add(cookie);

This would create a new cookie, add the data to it and then pass it down the stream. It must be noted that you also need to work with a dictionary (key-value pairs) in this HttpCookie thing too. To get the value from this Cookie, just simply use this, modify the code as this one,

if(Request.Cookies["form-data"] != null) {
    // if the cookie exists, so now get the value
    var name  = Request.Cookies["form-data"]["name"];
    if(name == "Secret-Name") {
        // name matches
    }
    Response.Redirect("~/first-page.cshtml");
}

In the above code, you will find almost same code used for the Session variables. That is because HttpCookies can also be cleared out by the OS, Browser, or by the User himself before you can ever try to clear them out yourself to create a condition. If you donot check it that way, you might get into a NullReferenceException to be thrown.

Final Conclusion

Only these three methods are not the total methods defined in (or used by)  ASP.NET to let you share the data among different classes and objects that is passed by the user to work on it. But instead you can have many more functions, such as using a QueryString to be passed down to the user through the URL to change the web page’s layout, using that QueryString.

In my opinion, Session variables and the Form method of doing this is a better way, to store the data for a longer time use Session variables, avoid Cookies because they can be directly accessed by the users, and also they load your HttpRequests making the networking slower between your server and the client.

It is also recommended that you should never (ever) save any sensitive data inside the Cookie or Session variable. Because they can be checked for the values inside the File System and might expose any sensitive data, such as credit-card information or passwords for the users. Always encrypt the data before passing it down to the user. Data of the user must be of utmost importance and their privacy and security must be taken care of with a priority.

Using POST request method is preferred to hide the data sent by the user in the URL, but always you must not consider that there is any security being added by the POST method. the sent data is still available in the context of the application’s Request object.

Points of Interest

Sharing the same data throughout the website is of great interest and great importance. ASP.NET lets you use forms and their data to be passed on to a new page where you will work on them. You can set an action attribute to the form to pass the data to which ever page.

ASP.NET also provides a special object, known as Session that can be used to share the data among different pages, this data is available to the web pages until the session is live, once the session is cleared out the data assosiated is also cleared. For more on ASP.NET’s Session, please read this MSDN document. The property document can be found at this web page.

You can also set the Cookies, to store the data on the Cookie to access it later by the server-side code. These cookie can be deleted by the user, browser or from the code-behind. Cookies documentation in ASP.NET can be found at this MSDN document and the HttpCookie class can be read at this MSDN document.