• No results found

Understanding Postback, Events, and Code-Behind

Book VIII: Advanced ASP.NET Programming

Chapter 4: Understanding Postback, Events, and Code-Behind

Postback, Events, and Code-Behind

In This Chapter

Posting pages to the server

Working with events in Visual Basic

Working with events in C#

Getting behind the scenes of code-behind

T

hree of the most important concepts in ASP.NET programming are the ideas of (1) posting pages to the server, (2) handling events, and (3) code-behind. Postback refers to what happens when the user clicks a button or performs some other action that sends the page displayed in the browser window to the server so whatever data the user entered on the page can be processed. Events are the processes that ASP.NET uses to deal with user interaction when a page has been posted. And code-behindis how ASP.NET lets you separate the code that’s executed when events occur from the markup code that defines how pages appear.

This chapter introduces you to these three all-important ASP.NET concepts. All code listings used in this book are available for download at www.dummies. com/go/aspnetaiofd.

Understanding Postback

You’re probably familiar with Web pages that include a Submit button. For example, consider a typical search-engine Web page that has a text box and a Submit button. When you click the Submit button, the text you entered into the text box is sent to the search-engine’s server, which looks up the results of your search and sends the results back to the browser. The process of sending the page to the server is called a postback.

Note that the term postbackimplies that the ASP.NET page has already been displayed in the browser. When the user clicks a button, the page along with any data entered by the user is sent to the server. The server then runs the code associated with the page to process the data entered by the user.

Using the IsPostBack Variable

54

When a page is posted, ASP.NET gets busy with the following tasks:

1.

ASP.NET receives the data sent back to the server, including any data that the user entered into controls such as text boxes.

2.

ASP.NET determines which page in the application was displayed in the browser window and loads that page into memory on the server.

3.

The properties of any controls that appear on that page are set based

on the data entered by the user.For example, if the page contains a text box and the user entered data into that text box, the Textproperty of the text box is set to the data value entered by the user.

4.

A special variable named IsPostBackis set to True. This enables the application to determine if a postback is occurring.(The next sec- tion digs into how to make this process happen, and explains why it’s significant.)

5.

The code that handles events generated for the page is executed.(For more about what that means, flip ahead to the later parts of this chapter, and look for the section “Understanding Events.”)

6.

After all of the event code has been executed, the page is sent back to the browser in the form of HTML so the user can see whatever updates have been applied to the page.

One important thing to know about the way ASP.NET applications work is to realize that not every type of control causes the page to be posted back to the server. For example, when a user selects an item from a drop-down list, the page isn’t normally posted. Nor is the page posted when the user selects a check box or radio button or enters a value into a text box. The user has to click a button to post the page. (As described in Book 2, you can change the behavior of controls such as drop-down lists and check boxes so they do post back when the user selects them — but don’t post the page by default.)

Using the IsPostBack Variable

A postbackoccurs only when the user clicks a button or performs some other action that causes the page currently displayed by the browser to be sent back to the server. The first time a page is retrieved by a user, a post- back doesn’t occur. For instance, when the user starts the Simple Calculator application (our example from the previous chapter of this mini-book) by browsing to the application’s Default.aspxpage, the page is loaded into server memory and events are processed, but a postback doesn’t occur. (In the case of the Simple Calculator application, a postback doesn’t occur until the user clicks the Add button.)

As you’ll see throughout this book, you’ll often write code that checks to see if a postback has occurred. For example, suppose you want to initialize the

Book I Chapter 4 Understanding Postback, Events, and Code-Behind

Understanding Events

55

Textproperty of a label to “Good Morning!”the first time a page is posted, but to change the label whenever the user posts back to the page by clicking a button; then the label should display “Hello Again!”instead of “Good Morning!”In that case, you might write Visual Basic code that looks like the following:

If IsPostBack Then

lblGreeting.Text = “Hello Again!” Else

lblGreeting.Text = “Good Morning!” End If

If you’re working in C#, the code would look more like this:

if (IsPostBack)

lblGreeting.Text = “Hello Again!”; else

lblGreeting.Text = “Good Morning!”;

Either way, the IsPostBackvariable is used to determine whether a post- back has occurred — if it has, the label’s Textproperty is set accordingly. Careful how you use this one. Using IsPostBackincorrectly can lead to all sorts of programming problems. If you find that a variable or field is incor- rectly reset to the same value each time the page is posted, you may need to add an ifstatement to set the variable or field only when IsPostBackis false.

You’ll see many more examples of the IsPostBackvariable in use through- out this book.

Understanding Events

Events are the key to ASP.NET programming because most of the code you write for an ASP.NET application is executed in response to events that are raised as a page is processed. In essence, an ASP.NET application consists of two things:

A set of Web pages that contain controls that users can interact with.

When a user interacts with one or more of the controls on a page, an event is generated to record the interaction.

Code executed in response to the events generated when the user interacts with the controls on the Web pages.

For example, consider the Simple Calculator application presented in the previous chapter of this mini-book. In practical terms, it’s a Web page that

Using the Handles Clause in Visual Basic

56

displays some labels, text boxes, a button, and some code that’s executed when the user clicks the button.

Button-click events are among the most common types of events — but by no means the only events — that ASP.NET pages encounter. Every time a page is posted to a Web server, a series of events are processed — or raised — by the ASP.NET server. In particular, the following events are always raised every time a page is posted:

✦ Preinit:This is the first event raised as a part of page initialization. It occurs before ASP.NET initializes the page. It allows you to change prop- erties that may affect the way the page is initialized.

✦ Init:This event occurs after ASP.NET has initialized the page; it allows you to add additional initialization code.

✦ Load:This event kicks in after the controls have been initialized with their correct values.

Control events:Any events that result from the user interacting with controls, such as when the user clicks a button or selects an item from a drop-down list, are raised after the Load event. For example, if the user clicks a button, the Click event will be raised after the Load event. Note that it’s entirely possible (and quite common) for more than one control event to occur each time a page is posted. For example, if a user selects an item from a drop-down list, clicks a check box to select it, then clicks a button, the page is posted when the button is clicked. Then three events are raised after the Load event: one to indicate that the user has selected an item from the drop-down list, a second to indicate that the user has clicked the check box, and a third to indicate that the user has clicked the button.

✦ PreRender:This event is raised after all of the control events have been raised but before the HTML that will be sent back to the browser is generated.

✦ Unload:This event is raised when the page has been sent back to the browser.

The process of connecting a method (or, as it’s called in VB.NET, a Subpro- cedure) to an event is called wiring.There are two ways to wire events, depending on whether you’re working in Visual Basic or C#. The next two sections describe the two techniques. (Hint: No screwdriver required.)

Using the Handles Clause in Visual Basic

The Handlesclause is it a piece of classical Christmas music (say, what Handel wrote right after he finished Messiah)? Nope. It actually refers to a clause you can add to a Subprocedure in Visual Basic. Its job is to designate

Book I Chapter 4

Understanding

Postback, Events,

and Code-Behind

Using the Handles Clause in Visual Basic

57

that the procedure should be invoked when a particular event is raised. In short, the Handlesclause is what links controls in an .aspxfile to proce- dures in a Visual Basic code-behind file. (The Handlesclause only applies to VB.NET programs. For a look at how events are handled in C#, refer to the next section.)

The format of the Substatement with a Handlesclause is as follows:

Protected Sub name(parameters) Handles control.event End Sub

For example, here’s a Subprocedure that handles a button-click event:

Protected Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button1.Click Button1.Text = “Got me!”

End Sub

Here, the Textproperty of the button named Button1is changed to “Got me!”when the button is clicked.

The Subprocedure has two parameters, named senderand e. The sender

parameter refers to the control that generated the event, in this case,

Button1. The eparameter provides additional arguments that might be useful to the event handler. (For more information on event handler argu- ments, you can look up System.EventArgsin the Visual Studio help.) Fortunately, you don’t have to worry about coding the Handlesclause — or the parameters — if you don’t want to. Instead, you can simply double-click a form control in the Web Designer view. Then Visual Studio automatically creates an event handler with the proper Handlesclause and parameters. Note that it’s possible for a single Subprocedure to handle an event for two or more controls. Here’s an interesting, if not very practical, example:

Protected Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) _

Handles Button1.Click, Button2.Click If sender Is Button1 Then

Button1.Text = “”

Button2.Text = “Click me!” Else

Button1.Text = “Click me!” Button2.Text = “”

End If End Sub

In this example, the text “Click me!”jumps from button to button when the user clicks either Button1or Button2.

Designating an Event Handler in C#

58

Designating an Event Handler in C#

C# doesn’t have an equivalent to Visual Basic’s Handlesclause. Instead, C# programs take a different approach to designating the code that is executed in response to events. Instead of specifying the event handling in the code- behind file, you specify it in the .aspxfile by adding an OnEventattribute to the tag for the control. For example, here’s the code for a button that speci- fies an event handler:

<asp:Button ID=”btnAdd” runat=”server” Text=”Add” OnClick=”btnAdd_Click” />

Here the OnClickattribute indicates that the method named btnAdd_Click

should be executed when the user clicks the button. In the code-behind file, the btnAdd_Clickmethod makes no reference to the btnAddcontrol or the

Clickevent. Like Visual Basic event handlers, however, C# event handlers must specify the senderand eparameters. Here’s an example:

protected void btnAdd_Click(object sender, EventArgs e) {

}

Once again, you don’t have to worry about coding these parameters or the OnEventattributes yourself. Simply double-click a control in the Web Designer and Visual Studio will automatically create an event handler for you with the correct OnEventattribute and the correct parameters. Note that Visual Basic also lets you use the OnEventtechnique to handle events. However, the Handlesclause is more common in VB.NET because Visual Studio uses it for generated code.

Using C#’s Auto Event Wireup

In addition to the OnEventtechnique described in the previous section, C# uses a technique called auto event wireup to automatically call the methods that handle page-level events such as Initand Load. Then all you have to do to handle these events is create a method with the appropriate name in the code-behind file. The following methods are automatically wired:

✦ Page_Init:Wired to the Initmethod for the page. This method exe- cutes after the page is initialized.

Book I Chapter 4 Understanding Postback, Events, and Code-Behind

Understanding Code-Behind

59

✦ Page_PreRender:This method executes after all control events for the page have been executed, but before any HTML has been generated for the page.

✦ Page_Unload:This event is typically where you put any cleanup tasks required by the application, such as closing files or terminating database connections.

Auto-event wireup is controlled (no surprise) by the AutoEventWireup

attribute on the Pagedirective that appears at the top of every .aspxfile. For example:

<%@ Page Language=”C#” AutoEventWireup=”true”

CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

When you use Visual Basic, AutoEventWireupis set to False. Then the methods that handle page-level events must specify a Handlesclause, as in this example:

Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load End Sub

Understanding Code-Behind

Code-behind is one of the most important concepts (and techniques) in ASP.NET programming. It uses a separate file to contain the VB.NET or C# code that’s executed in response to events — and only that code — rather than intermingling the VB.NET or C# code with the .aspxcode that defines the Web page.

The main benefit of code-behind is to separate the code that defines the appearance of a Web page from the code that defines the behavior of the page. Result: code that is easier to write, debug, and maintain. And it lets you direct your focus while you’re developing your applications. You can begin by creating a basic page that has the controls you need, without worrying too much about how the page looks. Then you can focus on getting the code to work so the page does its job correctly. After you have the code working, you can return to the .aspxfile to refine the appearance of the page.

In the real world, there isn’t always a clean separation between the appearance of a page and its behavior. Often, as a result, you end up alternating between tweaking the .aspxfile and tinkering with the code-behind file; changes in one file inevitably affect code in the other file. Even so, separating the appearance- making code from the behavioral code is a big step forward.

Using Single-File Pages

60

To understand how code-behind works, you need to understand two things: partial classes and code generation.

A partial class is a VB.NET or C# class defined by two or more files.

Partial classes are integral to code-behind because a Web page must be defined by a single class that represents the controlson the page (that is, the appearance of the page) as well as the event handlersfor the page (that is, the behavior of the page). The code-behind file is a partial class that supplies the methods that handle events. The other part of the class is what the .aspxfile provides.

Code generation (that is, the automatic creation of code) is a required

step because the .aspxfile is not written in either C# or Visual Basic.

Instead, it consists of a mixture of HTML and ASP.NET markup tags. When ASP.NET processes a page, it reads this markup and then generates C# or VB.NET code — which represents the page, its HTML, and all its con- trols. This code is a partial class that matches the partial class repre- sented by the code-behind file.

Thus the complete processing for an ASP.NET page consists of the following events:

1.

The .aspxfile is processed by ASP.NET, which generates a source file that defines a partial class that represents the HTML and controls for the page.This source file is generated in C# or VB.NET, depending on the language specified for the page.

2.

The source file generated in Step 1 is compiled by the C# or VB.NET compiler to create a partial class.

3.

The code-behind file is compiled by the C# or VB.NET compiler to create a partial class.

4.

The partial classes created in Steps 2 and 3 are combined to create the complete class that represents the page.

5.

The resulting class is loaded into memory and executed.

Using Single-File Pages

Code-behind isn’t the only code model supported by ASP.NET. If you prefer, you can also mix code directly in the .aspxfile, eliminating the need for a code-behind file. To do so, you simply uncheck the “Place code in separate file” option when you create a new Web page. Then, Visual Studio inserts