8.1. Understanding Web Forms


Before we build the application, it really is essential to provide a quick overview of the ASP.NET application architecture . Please bear with me, we'll be writing real code in no time.

The key to ASP.NET is the creation and interaction of web forms, which implement a programming model in which web pages are dynamically generated on a web server for delivery to a browser over the Internet. With ASP.NET Web Forms, you create an ASPX page with more or less static content consisting of HTML and web controls, and you write Visual Basic 2005 code to add additional dynamic content. The Visual Basic 2005 code runs on the server, and the data produced is integrated with the declared objects on your page to create an HTML page that is sent to the browser.

There are three critical points to pick up from the previous paragraph. Keep them in mind throughout this chapter.

  • Web pages can contain both HTML and web controls (described later).

  • All processing is done on the server (you can have client-side processing with scripting languages, but that is not part of ASP.NET and is not covered in this book).

  • If you use ASP.NET web controls, what the browser sees is just HTML (there is an exception to this; with some modern browsers, script may be sent as well). That is, even though ASP.NET web controls provide a new way to create web applications, by the time the page is sent to the browser, it is vanilla HTML.

ASP.NET 2.0 Web Forms are the successor to the enormously successful ASP.NET 1.x Web Forms, which, in turn, were the successor to ASP pages. The goal of ASP.NET 2.0 was to reduce the amount of coding by 70% compared to ASP 1.x. This means that web programming is increasingly declarative rather than programmatic that is, you declare controls on your web form rather than writing (and rewriting) boiler-plate code.

You still have the option of writing code (you can always write code) but for the vast majority of the web programming you do, you'll write a lot less code with ASP.NET 2.0 than you did with 1.x.


Web forms are designed to be viewed through any browser, with the server generating the correct browser-compliant HTML. You can do the programming for the logic of the web form in any .NET language. We will, of course, use Visual Basic 2005. Since Visual Studio makes the process of designing and testing web forms much easier, this book will use nothing but Visual Studio 2005 to develop web applications.

Web forms divide the user interface into two parts: the visual part or user interface (UI ); and the logic that lies behind it. This is very similar to developing Windows Forms. The division between the file that contains the user interface, and the corresponding file that contains the code, is called code separation, and all the examples in this book will use code separation, though it is possible to write the Visual Basic 2005 code in the same file with the user interface content (e.g., HTML).

In Version 2.0 of ASP.NET, Visual Studio takes advantage of partial classes, allowing the code-separation page to be far simpler than it was in 1.x. Because the code-separation and the declarative page are part of the same class, Visual Studio can hide its initialization code in a separate file.


The UI page is stored in a file with the extension .aspx. When you access the page through your browser, the server runs any associated code and then generates HTML that is sent to the client browser. Your ASP.NET application makes use of the rich web controls found in the System.Web and System.Web.UI namespaces of the .NET Framework Class Library (FCL) .

With Visual Studio 2005, web forms programming couldn't be simpler: open a form, drag some controls onto it, and write the code to handle events. Presto! You've written a web application.

On the other hand, even with Visual Studio 2005, writing a robust and complete web application can be a daunting task. Web forms offer a very rich UI and there are a great many web controls available to you to simplify your work, yet the very variety can be overwhelming at first.

8.1.1. Web Form Events

Much like the Windows Forms you built in Part I, web forms are event-driven. An event represents the idea that "something happened."

An event is generated (or raised) when the user presses a button, selects from a list box, or otherwise interacts with the UI. Events can also be generated by the system starting or finishing work. For example, open a file for reading, and the system raises an event when the file has been read into memory.

The method that responds to the event is called the event handler. Event handlers are written in Visual Basic 2005 and are associated with controls in the HTML page through control attributes.

By convention, ASP.NET event handlers are subs (not functions) and take two parameters. The first parameter represents the object raising the event. The second, called the event argument, contains any information specific to the event. For most events , the event argument is of type EventArgs, which does not expose any properties and is really just a placeholder. For some controls, however, the event argument might be of a type derived from EventArgs that can expose properties specific to that event type.

For example, when you bind a row to a GridView (see Chapter 10), an event fires that passes in a GridViewRowEventArgs object that derives from EventArgs. The GridViewRowEventArgs object has a Rows property, which returns a collection of GridViewRow objects. These, in turn, provide access to all the attributes of the corresponding rows, including the underlying data object (DataItem) that is being used to populate that row.

In web applications, with the exception of client-side script event handling, which is not covered in this book, events are handled on the server and, therefore, require a roundtrip. ASP.NET only supports a limited set of events, such as button clicks and text changes. These are the events that the user might expect to cause a significant change, as opposed to the myriad events handled in Windows Forms applications (see Part I), such as mouse events that might happen many times during a single user-driven task.


8.1.2. Event Model

The two models of program execution (which are not necessarily mutually exclusive) are linear and event-driven.

Linear programs move from step 1, to step 2, to the end of all the steps. Flow control structures within the code (such as loops, If statements, function or subroutine calls) may redirect the flow of the program, but essentially, once program execution begins, it runs its course unaffected by anything the user or system may do. Prior to the advent of GUI environments, most computer programs were linear.

In contrast, event-driven programming responds to something happening (such as a button being pressed). Most often, events are generated by user action, but events can also be raised by the system starting or finishing work. For example, the system might raise an event when a file that you open for reading has been read into memory or when your battery's power is running low.

In ASP .NET, objects may raise events and other objects may have assigned event handlers. For example, a button may raise the Click event and the page may have a method to handle the button's click event (e.g., Button1_Click). The event handler responds to the button's being clicked in whatever way is appropriate for your application.

8.1.3. ASP.NET Events

Classic ASP had just six events, of which only four were commonly used. These were:


Application_OnStart

Fired when the application started


Application_OnEnd

Fired when the application terminated


Session_OnStart

Fired at the beginning of each session


Session_OnEnd

Raised when the session ended

ASP.NET, on the other hand, has literally thousands of events. The application raises events, each session raises events, and the page and most of the server controls can also raise events. All ASP.NET event handlers are executed on the server. Some events cause an immediate posting to the server, while other events are simply stored until the next time the page is posted back to the server, to be executed at that time.

Because they are executed on the server, ASP.NET events are somewhat different from events in traditional client applications, in which both the event itself and the event handler are on the client. In ASP.NET applications, an event is typically raised on the client (e.g., by the user clicking a button displayed in the browser), but handled on the server.

Consider a classic ASP web page with a button control on it. A Click event is raised when the button is clicked. This event is handled by the client (that is, the browser), which responds by posting the form to the server. No event handling occurs server-side .

Now consider an ASP.NET web page with a similar button control. The difference between an ASP.NET button control and a classic HTML button control is primarily that the ASP.NET button has an attribute, runat=server, that allows the developer to add server-side processing to all the normal functionality of an HTML button.

When the Click event is raised, the browser handles the client-side event by posting the page to the server. This time, however, an event message is also transmitted to the server. The server determines if the Click event has an event handler associated with it, and, if so, the event handler is executed on the server.

An event message is transmitted to the server via an HTTP POST. ASP.NET automagically (that's a technical term) handles all the mechanics of capturing the event, transmitting it to the server, and processing the event. As the programmer, all you have to do is create your event handlers.

Many events , such as MouseOver, are not eligible for server-side processing because they kill performance. All server-side processing requires a postback (a roundtrip to the server and back), and you do not want to post the page every time there is a MouseOver event. If these events are handled at all, it is on the client side (using script) and outside the scope of ASP.NET.

8.1.4. Application and Session Events

ASP.NET supports the Application and Session events familiar to ASP programmers. An Application_Start event is raised when the application first starts. This is a good time to initialize resources that will be used throughout the application, such as database connection strings (but not the database connection itself). An Application_End event is raised when the application ends. This is the time to close resources and do any other housekeeping that may be necessary. Note that garbage collection will automatically take care of freeing up memory, but if you allocated unmanaged resources, such as components created with languages that are not compliant with the .NET Framework, you must clean them up yourself.

Likewise there are session events. A session starts when a user first requests a page from your application and ends when the application closes the session or the session times out. A Session_Start event is raised when the session starts, at which time you can initialize resources that will be specific to the session, such as opening a database connection. When the session ends, there will be a Session_End event.

Page events are wired automatically to methods with the following names:

  • Page_AbortTransaction

  • Page_CommitTransaction

  • Page_DataBinding

  • Page_Disposed

  • Page_Error

  • Page_Init

  • Page_InitComplete

  • Page_Load

  • Page_LoadComplete

  • Page_PreInit

  • Page_PreLoad

  • Page_PreRender

  • Page_PreRenderComplete

  • Page_SaveStateComplete

  • Page_Unload

8.1.5. Events in Visual Studio .NET

The Visual Studio .NET IDE can automatically handle much of the work required to implement events in ASP.NET. For example, Visual Studio offers a list of all the possible events for each control and if you choose to implement an event, you can type in a name for the event handler. The IDE will create the boilerplate code necessary and will wire up the associated delegate.

As you add controls, they will have their own events that you may handle as well. When you add the control, you can see its events by clicking on the control and then clicking on the events button (the lightning bolt) in the Properties window. For example, the events for a button are shown in Figure 8-1.

Figure 8-1. Button events


You may type the name of a method in the space next to any event or you may double-click in that space and an event handler will be created for you. You'll be placed in the event handler itself, ready to implement the event.

Every control has a default event, presumably the event most commonly implemented for that control. Not surprisingly, the default event for the button class is the Click Event. You can create the default event handler just by double-clicking on the control. Thus, had you not created the Button1_Click event handler as shown earlier, you could open Design view and double-click on the button. The effect would be identical: an event handler named Button1_Click would be created, and you'd be placed in the event handler ready to implement the method.

The default events for some of the most common web controls are listed in Table 8-1.

Table 8-1. Default events for some ASP.NET controls

Control

Default event

Button

Click

Calendar

SelectionChanged

CheckBox

CheckedChanged

CheckBoxList

SelectedIndexChanged

DataGrid

SelectedIndexChanged

DataList

SelectedIndexChanged

DropDownList

SelectedIndexChanged

HyperLink

Click

ImageButton

Click

Label

None

LinkButton

Click

ListBox

SelectedIndexChanged

RadioButton

CheckedChanged

RadioButtonList

SelectedIndexChanged

Repeater

ItemCommand


8.1.6. Multiple Controls to One Event Handler

It is possible for a single event handler to handle events from several different controls. For example, you may have a generic button-click event handler that handles all the buttons on your form. The button that raised the event can be determined by testing the sender parameter. In the following code snippet, a button-click event handler casts the sender object (that is, the control that raised the event) to the Button type, then assigns the ID property of that button to a string variable.

     Protected Sub GenericButton_Click( _     ByVal sender As Object, _     ByVal e As System.EventArgs) Handles btnOrder.Click             Dim b As Button = CType(sender, Button) 'cast object to button             Dim buttonID As String = b.ID           'save the button ID properly     End Sub 

This can eliminate a great deal of duplicate code and make your program easier to read and maintain.

8.1.7. Postback Versus Non-Postback Events

Postback events are those that cause the form to be posted back to the server immediately. These include click-type events, such as the button-click event. In contrast, many events (typically change events) are considered non-postback in that the form is not posted back to the server immediately. Instead, these events are cached by the control until the next time a postback event occurs.

You can force controls with non-postback events to behave in a postback manner by setting their AutoPostBack property to true.


8.1.8. State

A web application's state is the current value of all the controls and variables for the current user in the current session. The Web however, is inherently a "stateless" environment. This means that normally every post to the server loses the state from previous posts, unless the developer takes the trouble to preserve this session knowledge. ASP.NET, however, provides support for maintaining the state of a user's session.

Whenever a page is posted to the server, the server recreates it from scratch before returning it to the browser. ASP.NET provides a mechanism that automatically maintains state for server controls (the ViewState property) independent of the HTTP session. Thus, if you provide a list and the user has made a selection, that selection is preserved after the page is posted back to the server and redrawn on the client.

The state of other objects (that are not controls) is not automatically maintained in ViewState and must be stored by the developer, either in ViewState or in Session State, described in later sections.

The HTTP Session maintains the illusion of a connection between the user and the web application, despite the web being a stateless, connectionless environment.




Programming Visual Basic 2005
Programming Visual Basic 2005
ISBN: 0596009496
EAN: 2147483647
Year: 2006
Pages: 162
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net