Website Development
 
Get Your
Professionally Designed
Website and CMS
which contains everything needed for your online success
<h2>Programming Articles</h2>
 

Programming Articles

Minimize
Events and Postback 2008-06-21
Category: Web Development with Csharp
In this lesson we are going to look at how to handle events and set properties in code on the server. It is much the same as in many other languages, with the difference of mindset. Normally theses settings take place on the client, in a windows application. But because the web is a disconnected application, the mindset has to change slightly when dealing with web apps. But if you understand events and properties in other languages, this will be no different.

Events and Postback

by Robert Bravery
June 21, 2008
What about events and post back?

Well we are back. Hope you’ve enjoyed the lessons so far. Well at least as much as I have enjoyed preparing them.

Just one apology. I am currently working in the full version of Visual Studio 2008. There are some differences between this version and the Express version of Visual Web Developer. I will try and keep those differences in mind. But if I miss some, be free to point this out to me so that we can share it with the others. Essentially it should be 98% the same, so I don’t expect many problems.

In this lesson we are going to look at how to handle events and set properties in code on the server. It is much the same as in many other languages, with the difference of mindset. Normally these settings take place on the client, in a windows application. But because the web is a disconnected application, the mindset has to change slightly when dealing with web apps. But if you understand events and properties in other languages, this will be no different.

We will also be talking about a concept called postback. We will also see how to determine if the current web request is as a result of postback or first time request. Why does that even matter. Why do we need to watch for it. How does it affect our code and the resultant web page?

They probably talk about the events and properties that sit at a global level. These reside at the session and application levels.

Review

Now just in review. Remember we spoke about asp.net assemblies and that all the code that you write, the logic of your application resides in theses assemblies. The individual aspx pages contains a @Page directive, which points to the appropriate class in the assembly. Typically with the same name as the aspx page. So when a page request is made the asp.net engine sends information about whether this request is as a result of a postback or a first time request, as well as which event triggered the request. Like a button click event. You can then handle these events in your code. The asp.net engine delivers the request to the events handler which is where you write the logic for your site.

Again, you don’t have to worry about how this stuff works, just take comfort in the fact that is just does, and that the asp.net framework handles all this stuff for you. You are then left to focus on the logic and business of your application.

Why worry about understanding postback then?

After I just said forget about trying to know the inner dealings of asp.net, why then should we at least try and understand postback?

  1. Well first, postback is very cool, because is gives the impression of a rich UI (User Interface). Many web sites out there are static HTML pages with links on them to many other static html pages. Make no mistake, a lot of these pages are very well designed and appealing, but they lack that rich User Interaction. Postback gives that to you. Many of you have reservations about wether Web apps can do what windows apps do. Well postback is a step in that direction. It gives you the ability to have a rich UI and a rich user interaction and web experience. In some cases the user might even forget that they are on the web. Postback enables us to interact with the user change what they see, give them new information, or even give them a different web page. Now to do this without asp.net would require a lot of custom java programming.
  2. Secondly, sometimes postbacks can become confusing. When does it happen? What do I do about it? If we do not understand the basics of postback, we can get very confused and wonder why our web app is not behaving the way we expect it to behave.
So let’s get started.

Create a new web application/website. Name it whatever you want, I called mine Webapplication3. Switch to design view, if you have not already. Put two text boxes on the page and drop a button on the page. We now want to handle the click event for the button. Double click the button. An event handle will be automatically created for you in your code behind file. Note: Whenever you double click on a control the default event handler is created, so for a button it would be onclick. Then type in the following:

TextBox2.Text = TextBox1.Text;

Simple we want the text in textbox2 to have the same text in textbox 1 when we click the button. Simple hey!

At this point lets run our application to prove that it works. You will be prompted if you want to run with debugging, we spoke obout this in a previous lesson, click Ok.

When the page comes up in your browser, type something into textbox1 and click the button, notice textbox2 then contains whatever you typed into the first textbox. Not rocket science. Our app works. The event is raised, and we handle that event, do stuff and pass that back to the user.

Form load event.

Just like there is a form load event in windows forms, there is something similar in web forms, but it is called “Page Load Event”. Why? Well because we are dealing with web pages. This event fires each time a page is requested from a web browser.

So in design view, double click anywhere in the white area of your web page, and notice the default event created for you, which is the Page_Load event. So what might we use this page_load event for? Well, most likely for some initialization stuff, of setting some default stuff, or some other logic that must run before the page is presented to the user. The thing to remember though is that this event is loaded everytime the page is loaded. Even though the page is posted back once, twice three times, or even more.

So lets try it out. Suppose we want to initialise the textbox value to some text. So type the following in the Page_Load event handler

TextBox1.Text = string.Empty;

Quick Note: The string class behaves just like any other class. Here we are retrieving a Empty property of the string class.

This seems simple enough. What we want to do is reset the text of textbox1 to an empty string when the page loads.

Lets save, run and test.

As you run the app and when it comes up in the browser notice that the TextBox1 is empty, exactly what we expect. Now type something in and click the button. OOPs what went wrong there, I thought that the textbox2 should contain the text I typed in textbox1. After all thats what I told the thing to do in the buttons click event. What happened, what broke?

Well lets have a look at that. Actually nothing broke, as you know programs do exactly what you tell them to do. Its all a matter of order. Whats happening is that the page load event is firing before the button click event. So in our code we are setting the text in thextbox1 to empty, overwriting what we just typed in there, and then in the button click event, setting textbox2 to what is in textbox1, which in fact is an empty string.

Now the question is, how do we overcome or workaround this? Well the good news is that there is a way to check for this. We can check to see if this is the first request or not. The way to do that is to use a property of the page object, which relates to postback. This is why its important to at least understand something about postback. Now the page object contains a bunch of usefull properties and events pertaining to the current request and the current response of the current page. But the one we are interested in is a property called IsPostback. That's right. What we are checking is, is this request as a result of a postback? or is this the first time the page is rendered?

So change the code in the page_load event to look like this:

if (!Page.IsPostBack)

TextBox1.Text = string.Empty;

 Tip: Highlight your line from end to beginning, right click on the highlighted text, from the popup-menu select Surrounds with ... then scroll to if and select. Notice that the if code block is created for you, with your code inserted in between the curly braces. You can do this with any of the C# code blocks.

Note: The ! equates to not. So != would equate to not equal.

So what we are checking here is, is the current page request as a result of a postback or not, if not, then make the text empty, pr else leave is as it is.

One more thing to do to test this is set the text property to some text in the designer. In your Default.aspx page, select the design view, go to the properties window, and set the text property to something. I set mine to “OOPS”.

Run and test. First thing you notice is that your original text that you set is not there, Which is correct because we checked to see if the page was as a result of a post back. When the page is first loaded then it is not as a result of a post back, therefore the code that is executed changes the textbox text value,

Now type something into the textbox1 click the button. Now the current page request is as a result of a post back, and the code to set the text to an empty string is skipped, and then the code in the button click event runs. What I am trying to demonstrate here is an understanding of postback.

Lifetime of a web app.

Let’s talk a bit about the lifetime of a web application. The first time a request is made from a browser for any page in our web site a special object is created called the Application object. This object is maintained by the asp.net runtime engine. This is global across all pages and across all web visitors. This object is only removed if the application is stopped at the server level, if  IIS is stopped and restarted, or the application is idle for a long time, whereby the application is recycled out of server memory. Similarly another object is created, called the session object. This session object is global across the web site, but is not for the user. In fact a new session object is created for each user to your web site. Because of this, use with caution. You do not want to load hundreds of variables into the session object for a very busy site. Imagine that if the session object is alive for 20 min, and you have 100 users per minute, and you store 100 variables in the session object. You can soon see how quickly memory can be consumed.

So lets look at how to handle the four events associated with the application and session. Events that occur when the application starts and ends, and when the session starts and ends. In order to handle theses events we have to add a special file to our project called a Global.asax page. To do this click on the add new items button in your tool bar. Select “Global Application Class”, leave the default name. When that is done, you will see a new page. In your design view you will have a new page called Global.asax.cs. In it, will be some default events handlers. Notice the four events handlers:

  1. Application start
  2. Session Start
  3. Application end
  4. Session end.

So we can write code to handle these events every time they are triggered. So what can this be used for?Well we can initialise some stuff, keep track of some stuff. One thing that can be done is to keep track of users to your web site. 

In the application start type:

Application["userCount"] = 0;

This is the short way of writing this. The proper way would be:

Application.Add("userCount", 0);

What we are saying is create a variable in the application object with the key name of “userCount” and set its initial value to 0.

Then in the session start event type:

Application["userCount"] = (int)Application["UserCount"] +1;

This brings me to mention a thing about unboxing. Notice that there is an (int) infront of Application["UserCount"]. This is because Application["userCount"] is an object containing an int value. In order to use it we need to unbox it to an int, then we can add a value to it, and finaly store it back in the application object under the “userCount” key. We will talk about boxing and unboxing at a later stage. I just wanted you to be made aware of that.

Now in the session end event do the same, but decrement the value like:

Application["userCount"] = (int)Application["UserCount"] - 1;

Next we want to show onscreen what the user count is. Go to the code behind file. In the page_load eventhandler after the if codeblock write the following:

Page.Response.Write("User Count = :" + Application["userCount"].ToString());

Every page has a response object, and you can use the write method to write some kind of response to your HTML page. We have to string the “userCount” in the application object because it is in fact a boxed interger.

Run the application and test. Notice that the user count is 1. Copy the url, open a second browser, past the url and run. What is the user count now? It has incremented by one, simulating a second user. Go back to the first browser. Refresh the page. Notice that the user count has been incremented. Open up a third browser and see that you will get similar results. Now if we were to wait around for about 20 minutes for the session to end we will see that the user count gets decremented.

Print  
 
Contact Us Now
  Contact Us Now
Minimize
 

Email  us now or call us on 082-413-1420,  to host your website.

We design and develop websites. We develop websites that make a difference. We do Dotnetnuke Module development.

Web Masters Around The World
Power By Ringsurf
Print