Exploring ASP.NET Pages
- Understanding Page Events
- Understanding Page Properties
- Understanding Directives
- Code Separation and Using Code-Behind
- Summary
Alive!!! It's alive!!...The page is ALIVE!!!!!
I don't want to sound like a nag or like I'm harping on the same issue over and over, but ASP.NET is really about events and objects. The ASP.NET page is no exception. It is an object in the eyes of ASP.NET just like anything else. It has properties and methods and can be interacted with, similar to the other objects you've seen so far, and the plethora of things to come as you move through the remainder of this book.
Because events are a big part of ASP.NET and also a huge part of the power of the ASP.NET page object, it's important to look closely at these event and the order in which they occur so that you can utilize them to their fullest potential.
Understanding Page Events
Maybe this isn't the best way to explain this. Maybe my mother wouldn't be so proud of my openness. Maybe these examples will be too graphic for you, but it's the best way I can describe it, so please bear with me.
Every morning of every workday I start my day the same way. I get up, drag my carcass into the living room, and turn on the television. I stare at overpaid morning show hosts like a dribbling fool, with about as much cerebral activity as an earthworm trying to figure out what to eat. After the first flicker of lights goes off in my cranium, I drag my carcass to the shower to defrost my brain.
In the shower I have a set routine so as not to miss any vital, proper hygienic functions and to ensure that the other people in my office and our clients don't give me those strange looks anymore when I enter the room. I think if you took the time to analyze this portion of your life, you'd see that without conscious thought, you pick up the bar of soap and proceed to cleanse without ever putting a thought into what you are doing. You may be singing or thinking about the day you are about to face and before you know it...Boom! You're finished.
It's a routine that I go through every morning almost without thought. And that's a good thing; if I needed to be able to think before I could shower, I wouldn't arrive at work until 10:00 a.m., or until I've had several cups of joe. This practice is part of a subconscious, programmed routine that has been burned into my mind from years of habit.
When I then go to work, I respond to the world around me. I make decisions based on what stimulus comes my way. Maybe someone comes to the office for a meeting. They ask questions and I answer them. The phone rings and I pick it up. I get e-mail and I occasionally read it and less often answer it. I am affected by the world around me and what kind of input it gives me. I then go home and enjoy the solace (this isn't a joke and I'm not kidding) of my family.
At the end of the day I get into my pajamas and go to sleep.
ASP.NET pages are a lot like this. They go through a routine every time they are called. These routines are the ASP.NET pages' events. They are like the steps I go through every morning to prepare for my day, or like showering by the same routine everyday.
ASP.NET pages have a routine of events that happen, and they happen in the same way, in the same order, every time. You've seen one of these events, Page_Load, in some of the previous examples. Let's look into these events and the others that a page goes through when it is executed.
The three main events, although there are others, are as follows:
Page_Init
Page_Load
Page_Unload
Page_Init
The Page_Init event is the first to occur when an ASP.NET page is executed. This is where you should perform any initialization steps that you need to set up or create instances of server controls. Server controls are discussed in later chapters, so just keep this event in mind.
You don't want to try to access controls in this event because there is no guarantee that they have been created yet. It is during this event that they are created, and you can control whether your attempt to use these objects will be thwarted by the server processing your request before the object has been created.
The following is an example of the structure of how to use the Page_Init event
Visual Basic .NET
Sub Page_Init() 'Place your Page_Init code here End Sub
C#
void Page_Init(){ //Place your Page_Init code here }
Note that the Page_Init event fires only the first time the page is loaded. When you use a web form and post back to this page again, the Page_Init event doesn't fire. But the Page_Load event fires each time the page loads.
Page_Load
This is the page event where you will be doing most of your work. This event occurs only when all the objects on the page have been created and are available for use. You will seewithin this book and in other examples available in the .NET Framework SDK and ASP.NET-related web sitesthat the lion's share of work on ASP.NET pages is done during this event. We've been using this event since the beginning of the book and will continue to use it in just about every example.
Although you've seen it a zillion times already in the book, for consistency's sake I'll show you the form here. It doesn't look a whole lot different from the Page_Init example, and for all intents and purposes the only thing that's different is that the word Init is substituted with the word Load.
Visual Basic .NET
Sub Page_Load() 'Place your Page_Load code here End Sub
C#
void Page_Load(){ //Place your Page_Load code here }
Page_Unload
Page_Unload is the counterpart to Page_Init. Just as Page_Init is an event that happens before anything else happens, Page_Unload happens after everything else happens. It is available for you to perform any operation you need to after you are completely finished with the page.
For instance, imagine that you temporarily needed to create a file on the server during the page's processing. You wouldn't want to leave it there for eternity, especially if the file was unique to each visitor of the web site. You could have loads and loads of files building on your server without any way to get rid of them. But if you were a good boy or girl, you could destroy the file during the page's Page_Unload event and make the server administrator a happy camper.
Just to be fair and impartial, I don't want to leave out showing you the structure of the Page_Unload event. Look familiar?
Visual Basic .NET
Sub Page_Unload() 'Place your Page_Unload code here End Sub
C#
void Page_Unload(){ //Place your Page_Unload code here }
Getting back to my morning routine, it looks like this:
Peter_Init. Roll carcass from bed to in front of the television.
Peter_Load. Take shower brainlessly, get dressed (make sure socks match and colors coordinatecheck with wife for confirmation). Get into car and drive to the office.
Handle the day in all its glory and all the blessings that come with it.
Peter_Unload. Get into jammies and go to sleep.
It's that routine, and I behave just like the Page object does. When I run through these events, I am investigating and affecting all kinds of things. I'm finding out the condition of the world that morning by listening to news, changing the state of my brain to somewhat functional, changing the direction that my hair points from an erratic bird's nest to some semblance of a hairdo, and more.
I'm doing this through checking and setting properties and executing methods, so to speak. During Peter_Init, I execute the RollCarcass() method to change the Peter.Sleeping property from true to false.
During Peter_Load I'm checking the value of the eye.bags property and seeing what the value of the hair.color property is, which is generally grayer than the day before. I'm assuring that the body.odor property is set to zero by executing the Shower() method.
I then have the ability to respond to events and stimulus from the world around me throughout the day. Then during the Peter_Unload event, I execute the CollapseFromExaustion() method to set the Peter.Sleeping property to true.
Can you see how these different events at different times have a direct affect on my condition? ASP.NET pages can be affected just like this with their different events. Now are you beginning to see more clearly how events and objects interact in ASP.NET and how this is a totally different paradigm from any traditional way of web programming in HTML or Active Server Pages.
As I said in the beginning of the chapter, ASP.NET is all about events and objects, and the ASP.NET page is no exception. You know that objects are made up of their properties and methods, and now you know that objects can also have events, as well.
The page object has the three mentioned events, as well as others that execute without intervention from the designer, but other events also affect ASP.NET pages.
User-Initiated Events
Just as I am faced with input from the world around me after the Peter_Onload event has finished, a page can also deal with events initiated by the web page's visitor.
Let's look at an example of some events, both self executing and user initiated. Below is a page that shows the date and asks you to pick what mood you're in. In the code samples, you'll also be shown another neat server control called a RadioButtonList and a cool feature of the .NET Framework called Databinding. You will also see a property of the Page object called IsPostBack. We will discuss this later in this chapter, but again, don't get hung up on these things just concentrate on the events in the page.
Visual Basic .NET
<%@ page language="vb" runat="server"%> <script runat=server> Sub Page_Load() dim TodaysDate as Date TodaysDate = DateTime.Now.ToShortDateString OurTitle.Text = "<u><b>Today's Date is " + TodaysDate + "</b></u>" If Not IsPostBack then dim MoodArray(3) as String MoodArray(0) = "Good Mood" MoodArray(1) = "Okay Mood" MoodArray(2) = "Bad Mood" MoodArray(3) = "Totally Melancholy " YourMood.DataSource = MoodArray YourMood.DataBind() End If End Sub Sub CheckMood(sender As Object, e As System.EventArgs) If YourMood.SelectedIndex > -1 then SelectedMood.Text = "The Mood that you selected is " +
YourMood.SelectedItem.Text Else SelectedMood.Text = "What? You don't feel anything?" End If End Sub </script> <html> <title>What's Your Mood?</title> <body> <form id="MoodForm" runat="server"> <asp:label id="OurTitle" runat="server"/><br> <asp:RadioButtonList id="YourMood" runat="server"/> <asp:Button id="MoodButton" text="What's Your Mood?" onClick="CheckMood"
runat="server"/> <br><br> <asp:label id="SelectedMood" runat="server"/><br> </form> </body> </html>
C#
<%@ page language="c#" runat="server"%> <script runat=server> void Page_Load(){ String TodaysDate; string[] MoodArray = new string[4]; TodaysDate = DateTime.Now.ToShortDateString(); OurTitle.Text = "<u><b>Today's Date is " + TodaysDate + "</b></u>"; if (!IsPostBack){ MoodArray[0] = "Good Mood"; MoodArray[1] = "Okay Mood"; MoodArray[2] = "Bad Mood"; MoodArray[3] = "Totally Melancholy "; YourMood.DataSource = MoodArray; YourMood.DataBind(); } } void CheckMood(object Source, System.EventArgs s){ if (YourMood.SelectedIndex > -1) { SelectedMood.Text = "The Mood that you selected is " +
YourMood.SelectedItem.Text; }else{ SelectedMood.Text = "What? You don't feel anything?"; } } </script> <html> <title>What's Your Mood?</title> <body> <form runat="server"> <asp:label id="OurTitle" runat="server"/><br> <asp:RadioButtonList id="YourMood" runat="server"/> <asp:Button id="MoodButton" text="What's Your Mood?" onClick="CheckMood"
runat="server"/> <br><br> <asp:label id="SelectedMood" runat="server"/><br> </form> </body> </html>
If you look at Figure 4.1, you can see the results of the initial load of the page. The Page_Load event fires, at which time the date is created. I then set the Text property of OurTitle and I build an array that will make up the radio buttons.
If you look back at the code samples again, you can see that attached to the button is an onClick event that calls a function called "CheckMood". I know that this looks pretty similar to a client-side JavaScript function call, but remember that ASP.NET is a server-side technology. If you look at the code delivered to the browser, you see that there is no onClick event to be seen.
<input type="submit" name="MoodButton" value="What's Your Mood?" id="MoodButton" />
Figure 4.1 The Page_Load event has built the page, but the onClick event hasn't had any effect because the button hasn't been pressed yet.
ASP.NET knows whether you pressed this buttonnot by a typical client-side onClick event, but by inspecting the form that is posted and seeing whether this button was pressed. The terminology is similar to client-side JavaScript, but the function and method is totally different.
Now it's time to pick a mood and click the button. You can see in Figure 4.2 that the mood is now displayed because the onClick event that took place server-side executed the function called CheckMood, which sets the text of the label.
Figure 4.2 The onClick event is fired by clicking the button.
To reinforce the point that ASP.NET is smart about calling functions and that what is executed is determined by the onClick event of the button, I have put together a sample with two different buttons that call two different functions. Each button uses its own onClick event.
Visual Basic .NET
<%@ page language="vb" EnableViewState="false" runat="server"%> <script runat=server> Sub CountDown(sender As Object, e As System.EventArgs) dim i as Integer for i = CDbl(Text1.Text) to 1 Step -1 OurLabel.Text += "Countdown: " + i.ToString() + "<br>" next End Sub Sub StringLength(sender As Object, e As System.EventArgs) OurLabel.Text = "The length of this string is: " + Text1.Text.Length.toString End Sub </script> <html> <head> <title>What do you want?</title> </head> <body> <form runat="server"> Either enter a word to find its length or a number to count down from<br> <asp:TextBox id="Text1" runat="server"/> <asp:Button id="btnCountDown" text="Count Down" onClick="CountDown"
runat="server"/> <asp:Button id="btnLength" text="Get Length" onClick="StringLength"
runat="server"/> <br><br> <asp:label id="OurLabel" runat="server"/><br> </form> </body> </html>
C#
<%@ page language="cs" EnableViewState="false" runat="server"%> <script runat=server> void CountDown(object Source, System.EventArgs s){ int i; for (i = Convert.ToInt16(Text1.Text);i >= 1;i){ OurLabel.Text += "Countdown: " + i.ToString() + "<br>"; } } void StringLength(object Source, System.EventArgs s){ OurLabel.Text = "The length of this string is: " +
Text1.Text.Length.ToString(); } </script> <html> <head> <title>What do you want?</title> </head> <body> <form runat="server"> Either enter a word to find its length or a number to count down from<br> <asp:TextBox id="Text1" runat="server"/> <asp:Button id="btnCountDown" text="Count Down" onClick="CountDown"
runat="server"/> <asp:Button id="btnLength" text="Get Length" onClick="StringLength"
runat="server"/> <br><br> <asp:label id="OurLabel" runat="server"/><br> </form> </body> </html>
If you look at Figure 4.3 you can see that after the Count Down button was clicked, with the value of 10 in the text box, the CountDown function was executed and the code generated and displayed properly.
Figure 4.3 Clicking the Count Down button causes the CountDown function to execute.
Now if you put a string such as "What is the length?" in the text box and click the Get Length button, you are executing the StringLength function.
NOTE
This example has a bit of hidden danger in that if someone enters a string in the text box and clicks the Count Down button, ASP.NET will cause an error. This is because it can't convert a String type to an Integer in this circumstance. But you don't need to worry about this in your real-world applications because ASP.NET provides some really, REALLY cool answers to validating input data (that we will be devoting an entire chapter to later). The validators would totally solve any issues like thisand more.
Figure 4.4 Clicking the Get Length button causes the StringLength function to execute.
As if all the objects and events covered earlier weren't enough, the concept of user-initiated events opens up a totally new way of thinking again about how you can handle and manipulate data, depending on how a user interacts with your web application.
Other events are also available that can help you manipulate data and objects, and I would encourage you again to go to the class browser located at the following link and look at what events you can use on each object:
http://samples.gotdotnet.com/quickstart/aspplus/
Now that we've touched on the different events, both default and user-initiated, let's move on to looking at some of the key properties of the Page object.