Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

Exploring ASP.NET Pages

Explore ASP.NET pages and dig into some of their core functions, such as page events and properties, and directives.
This chapter is from the book

This chapter is from the book

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 see—within this book and in other examples available in the .NET Framework SDK and ASP.NET-related web sites—that 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:

  1. Peter_Init. Roll carcass from bed to in front of the television.

  2. Peter_Load. Take shower brainlessly, get dressed (make sure socks match and colors coordinate—check with wife for confirmation). Get into car and drive to the office.

  3. Handle the day in all its glory and all the blessings that come with it.

  4. 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 button—not 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 this—and 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.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020