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 important 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 has 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 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 an easy 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 the only thing that matters is the data that is to be sent. You can use any method that you’ve already excelled 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 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 the 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 whatsoever 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 rendered, 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) { var name = Request["name"];
if(name == "Secret-Name") {
}
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 get 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
The 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 we can 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:
var name = Request.Form["name"];
Session["name"] = name;
An 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) {
var name = Session["name"].ToString();
if(name == "Secret-Name") {
}
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:
Session.Abandon() -
Cancels the current session
Session.Clear() -
Clears the session
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 a 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. The 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"];
example.Age = Convert.ToInt16(Request.Form["age"]);
Session["object"] = example;
Now, you can extract this object like this:
Example example = (Example)Session["object"];
Make sure that you’ve used the if else
block to avoid the NullReferenceException
being thrown.
Cookie, Cookie, HttpCookie
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"); cookie["name"] = Request.Form["name"]; 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) {
var name = Request.Cookies["form-data"]["name"];
if(name == "Secret-Name") {
}
Response.Redirect("~/first-page.cshtml");
}
In the above code, you will find almost the 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 do not 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 whichever 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 associated 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 cookies 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.
History
This is the first version of the post.