Our First Web Form

Our First Web Form

To give you an immediate sense of how powerful Web Forms are, we'll create a simple program that uses the new calendar control. The program will display a calendar from which the user must select a date before submitting the page. If a date is not selected, a field validator will notify the user and the page won't be sent.

Start a new ASP.NET Web application project with the name WebForms, as shown in Figure 13-1. Notice that the location of the file will be the local host. If you are running Internet Information Services (IIS) or Personal Web Server on the same machine as Visual Studio .NET, the local host will usually be C:\Inetpub\wwwroot.

Figure 13-1

Create an ASP.NET Web application named WebForms.

The default workspace for an ASP.NET Web application, shown in Figure 13-2, looks a bit different from what we're used to seeing. The toolbars are slightly different, and the design surface is white, but the overall feel is the same. (The message you see on the form is not part of our application; it's simply a note from Visual Basic .NET telling us which layout mode is being used.)

Figure 13-2

The default ASP.NET Web application workspace.

tip

To change the layout of the ASP.NET Web application workspace, right-click on the display area and select Properties. When the Document Property Pages dialog box appears, you can change the page layout. The page layout options you use will be primarily a matter of preference. The FlowLayout setting allows the user to add text and hard paragraph breaks to the page, which is converted into HTML code. When the default GridLayout setting is selected, the controls are placed on the surface of the page but are not interspersed with HTML code, as happens in FlowLayout. If you have ever used Microsoft FrontPage, you are familiar with the WYSIWYG style, which is a huge improvement over earlier designs.

The Solution Explorer reveals that a few more files are required when developing Web Forms rather than Windows Forms, as you can see in Figure 13-3. The classes that include the visual components are located in the System.Web namespace. Table 13-1 lists and describes the files in our WebForms project.

Figure 13-3

Web Forms applications have more files than Windows Forms applications.

Table 13-1  The Files in Our WebForms Project

File

Description

AssemblyInfo.vb

An optional project information file that contains metadata about the assemblies in a project, such as name, version, and culture information.

Web.config

An XML-based file that contains configuration information for ASP.NET resources.

Global.asax

An optional file for handling application-level events. This file resides in the root directory of an ASP.NET application. When deployed, this project's WebService1.dll file will contain the "code-behind" file associated with the .asax file. I'll be covering code-behind files shortly.

WebForms.vsdisco

An optional XML-based file that contains links (URLs) to resources providing discovery information for a Web service.

WebForm1.aspx

The user interface file we are now working with.

New Server Controls

If you take a look at the Web Forms tab in the toolbox, shown in Figure 13-4, you can see the names of quite a few new controls. These controls are referred to as server controls and are similar to the Windows Forms controls we've been working with. Each control provides a consistent set of properties and methods. In addition, these controls manage state, can be manipulated in code, and provide a limited set of events to which we can add our program logic.

Figure 13-4

Web Forms server controls.

Another set of controls available for Web Forms appears on the HTML tab, shown in Figure 13-5. These controls are referred to as HTML server controls. Each of these controls is basically a one-to-one match for the HTML controls found on current Web pages. These controls are not sophisticated and have no intelligence for handling how they appear with various browsers. HTML server controls were provided to update existing pages to the new server controls. Unless you are updating pages already created, I'd suggest you stick with the server controls on the Web Forms tab.

Figure 13-5

HTML server controls.

ASP.NET server controls are incredibly powerful. They have a more consistent and flexible object model than the ASP object model that is familiar to classic Visual Basic programmers. When a control is served to the client, it is rendered in HTML automatically. Server controls contain automatic browser detection logic and can customize and optimize their output. The new controls can also perform data binding.

In addition to the HTML server controls and the Web Forms server controls, we also have new validation controls. Field validation has always been the bane of ASP developers. Addressing the problem required a few more acres of code, but that's no longer the case. The validation controls are wired to a control such as a text box, and they take care of our needs, such as constraints on numeric-only or required fields.

Let's go ahead and add controls from the Web Forms tab to our designer. Add a text box, a calendar, a button, and a RequiredFieldValidator. Position the controls roughly as shown in Figure 13-6.

Figure 13-6

Add the controls shown here.

The HTML Presentation Template

Notice the Design and HTML options at the bottom of the designer window. A Web Form consists of two pieces: an HTML-based template that contains the layout of the page, and a code module that contains the code behind the page. Click the HTML tab to see the following code that will be sent to a browser. The code will look familiar to those of you who have worked with ASP. You really don't need to know how to read HTML, but this code provides insight into how Web Forms do their magic.

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebForms.WebForm1"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title></title> <meta name="GENERATOR" content= "Microsoft Visual Studio.NET 7.0"> <meta name="CODE_LANGUAGE" content="Visual Basic 7.0"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form method="post" runat="server"> <asp:TextBox style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 27px" runat="server" Width="233px"></asp:TextBox> <asp:Calendar style="Z-INDEX: 102; LEFT: 35px; POSITION: absolute; TOP: 61px" runat="server" Width="233px"></asp:Calendar> <asp:RequiredFieldValidator style="Z-INDEX: 103; LEFT: 44px; POSITION: absolute; TOP: 263px" runat="server" ErrorMessage="RequiredFieldValidator"> </asp:RequiredFieldValidator> <asp:Button style="Z-INDEX: 104; LEFT: 150px; POSITION: absolute; TOP: 295px" runat="server" Width="112px" Text="Submit"></asp:Button> </form> </body> </HTML>

The Structure of a Web Form

Visual Basic .NET Web Forms are based on a Microsoft ASP.NET technology in which code that runs on the server dynamically generates Web page output to the client browser. Take a look at the first line with the @Page directive.

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebForms.WebForm1"%>

Web Forms pages are built on the ASP.NET Page framework, which means that each Web Forms page is an object that derives from the ASP.NET Page class. Page objects are compiled and automatically cached.

A Page object also acts as a container for the various controls. When a user requests a Web Forms page from a server, the Page framework runs the Web Forms Page object and all the individual controls on it. It then converts the output of the Page class and of the controls to HTML that can be rendered in a browser. In addition, the Page framework supports controls that can be programmed for user interaction with your Web Forms pages. User actions in a form are captured and processed by the Page framework in a way that lets you treat them as standard events.

The @Page directive tag also defines characteristics of the page. First of all, the directive indicates that the language will be Visual Basic (instead of C#, for example). AutoEventWireUp determines whether the Page_Load event handler is automatically wired to the OnPageLoad event. Setting the value to False means that we need to provide our own code for this handler if required.

The next statement is the rather cryptic Codebehind = "WebForm.aspx.vb". This statement is necessary because the code that drives the page is actually placed in another file. This file is the code behind the interface defined in WebForm1.aspx. I'll examine that file in detail shortly, but briefly, it contains a class definition that is used as the base class for the Web Forms page. This particular base class will be used in conjunction with code in this file to generate the HTML that reaches the user. Web Forms essentially separate the user interface (WebForm.aspx) from the code that implements it (WebForm.aspx.vb). The Web Forms Page framework and the relationships between these files are shown in Figure 13-7.

Figure 13-7

The relationships between the Web Forms Page framework files.

Within the ASP.NET Page class model, the entire Web Forms page is really an executable program that generates output that is then sent to the browser. The ASP.NET Page class model makes developing a Web Forms application identical to developing a Windows Forms application, and it is a quantum leap in functionality for ASP developers. Separating our class, WebForm1.aspx.vb, as the code-behind file is not only easier to debug (trust me on this one), but you can now let the designers work on the user interface for a Web page while the programmers work on the code behind it all.

Our code-behind class WebForm1 inherits from the Page class that lives in the System.Web.UI namespace. The Page class contains the properties, methods, and events in the Web Forms page framework.

Public Class WebForm1 Inherits System.Web.UI.Page

Our user interface file, WebForm1.aspx, inherits from the code-behind class.

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebForms.WebForm1"%>

Both files are then compiled into a DLL that is run from the server.

The Controls

Web Forms server controls are referenced with the syntax <asp:ControlName>. All of the properties of the control are set within the <asp:ControlName ….> and </asp:ControlName> tags. The calendar control is given an ID of Calendar1, the default name of the calendar when it's drawn on the form. Then some style and location properties are set. Finally the critical runat="server" attribute is provided, which makes all of this code work.

<asp:Calendar style="Z-INDEX: 102; LEFT: 35px; POSITION: absolute; TOP: 61px" runat="server" Width="233px"></asp:Calendar> 

If the runat="server" attribute is left out, we are effectively providing client-side code, which will fail miserably if the control uses any server-side style coding. Note that the syntax for controls is based on XML, so you'll get an error if you inadvertently omit the closing tags.

The beauty of Web Forms server controls is that we have full access to their properties and events through the Properties window (just as we do with their Windows Forms brethren) and can receive instant feedback in the code or design environment whenever we make changes.

Viewing the Code-Behind File

Return to Design mode and choose Code from the View menu to display the code-behind file, WebForm1.aspx.vb. This file is where the Visual Basic .NET code we use to handle the logic for the page lives. By now you should be quite familiar with this code, so I won't spend time on it here.

Public Class WebForm1 Inherits System.Web.UI.Page Protected WithEvents Calendar1 As _ System.Web.UI.WebControls.Calendar Protected WithEvents TextBox1 As _ System.Web.UI.WebControls.TextBox Protected WithEvents Button1 As _ System.Web.UI.WebControls.Button Protected WithEvents RequiredFieldValidator1 As _ System.Web.UI.WebControls.RequiredFieldValidator #Region " Web Form Designer Generated Code " 'This call is required by the Web Form Designer <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() End Sub Private Sub Page_Init(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the ' Web Form Designer. 'Do not modify it using the code editor. InitializeComponent() End Sub #End Region Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here End Sub End Class

Setting the Properties on Our Web Page

Return to the design WebForm1.aspx form, and right-click the calendar control. Select Auto Format to bring up the Calendar Auto Format dialog box, shown in Figure 13-8. Select the Professional 1 scheme, and then click OK. Setting this property will make our page look pretty sophisticated.

Figure 13-8

The Professional 1 scheme provides a sophisticated look for a Web page.

Arrange the controls as shown in Figure 13-9, and then set the properties for the controls as listed in Table 13-2.

Figure 13-9

Arrange the controls as shown here.

Table 13-2  Properties for the WebForm Controls

Object

Property

Value

Text box

ID (like Name in Windows)

tbDate

Calendar

Keep defaults

Button

ID

btnSubmit

Text

&Submit

RequiredFieldValidator1

ControlToValidate

tbDate (from the drop-down list)

ErrorMessage

"Please enter a date!"

Adding the Calendar Control Code

Double-click the calendar control. The template for the SelectionChanged event handler will be created automatically. Add a single line of code that will take the date the user selects and display it in the text box. Notice that several built-in formats are available for us. In this example, we'll use the ToLongDateString format.

Private Sub Calendar1_SelectionChanged( _ ByVal sender As System.Object,_ ByVal e As System.EventArgs) _ Handles Calendar1.SelectionChanged  tbDate.Text = Calendar1.SelectedDate.ToLongDateString End Sub

Running the Web Form

Go ahead and run the Web Form by pressing F5. The browser is invoked, and your page is displayed, as you can see in Figure 13-10. Click the Submit button without selecting a date. Notice that the RequiredFieldValidator becomes visible and displays our error message. No code was required to accomplish this, which will make any grizzled ASP programmer smile. We were able to display this page—with a sophisticated calendar, text box, button, and field validation control—with only a single line of code. This is nothing short of amazing.

Figure 13-10

The WebForms application in action.

When the Submit button is clicked, the date is submitted back to the server. By default, a button control on a Web Form application is a submit button that posts data back to the server. You can provide an event handler for the Click event to programmatically control the actions performed when a submit button is clicked. In our case, we didn't write any code for the button. Still, when it is pressed, it attempts to post data back to the server. It couldn't here because the required field tbDate is empty.

Now select a date from the calendar, and click the Submit button once more. This time we are successful. The date is displayed in the text box in the long date format, as you can see in Figure 13-11.

Figure 13-11

The text box shows dates in the long date format.

Examining the HTML Sent to the Browser

Run the WebForms application again, but before you select a date, click the View Source menu option from Internet Explorer. I mentioned that ASP.NET pages and controls can remember their state between calls to the server. Let's see how this magic is accomplished. Examine the first few lines of the HTML our program sent to the browser.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title></title> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="CODE_LANGUAGE" content="Visual Basic 7.0"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form name="Form1" method="post" action="WebForm1.aspx" language="javascript" onsubmit="ValidatorOnSubmit();" > <input type="hidden" name="__VIEWSTATE" value="dDwtMzQ0NzE0MzI4Ozs" />

Notice the text string in the hidden input field with the name _VIEWSTATE. It is the hidden _VIEWSTATE field that encapsulates the state of the form. This information is used when the form is posted back to the server to re-create the user interface, keep track of changes, and so on. Essentially it holds the state of the form and controls.

Click a date on the calendar, and examine the source code from the browser again. Notice that the _VIEWSTATE string has grown quite a bit. It contains the selected date, changes to the calendar, and other information. As you can imagine, on sophisticated Web forms, this string can grow quite large.

<input type="hidden" name="__VIEWSTATE" value="dDwtMzQ0NzE0M zI4O3Q8O2w8aTwxPjs+O2w8dDw7bDxpPDM+Oz47bDx0PEAwPHA8cDxsPFNEO z47bDxsPFN5c3RlbS5EYXRlVGltZSwgbXNjb3JsaWIsIFZlcnNpb249MS4wL jI0MTEuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhN WM1NjE5MzRlMDg5PDIwMDEtMDktMjY+Oz47Pj47Pjs7Ozs7Ozs7Ozs+Ozs+O z4+Oz4+Oz4=" />

The _VIEWSTATE string will remember the form's state and thus any values that have been submitted. It's important to keep in mind that the server has nothing to do with maintaining this state information. Remembering the values is performed entirely by the _VIEWSTATE string. The server requires no resources to maintain the form's state and absolutely no state is being stored on the server. Instead, the values are posted to the server using standard methods. When the server posts back to the page, the _VIEWSTATE string prepopulates the form with the previous values.

The _VIEWSTATE string is an elegant method of storing a Web page's state. Because HTTP is a stateless protocol, Web pages are created from scratch each and every time a round trip between the server and the client occurs. After a Web page is served, the server is finished with the page and no further connection with the client is maintained. Web pages are stateless, and no values from Web page variables are maintained on the server. Not only that, but also in a Web server environment in which a user might get one page from one server and the next page from a totally different server (because of load balancing), using _VIEWSTATE permits the page to hold its own state. ASP.NET gets around this serious limitation and behaves as though the server remembers each and every detail of each page.

The Web Form state information is tokenized, which means it is translated into a compressed form. And because HTTP does not permit binary objects to be sent, the tokens are all text based. Preliminary tests at Microsoft have revealed that even with very long _VIEWSTATE strings, performance is comparable to other more complex state management techniques.

note

ASP.NET does not support Visual Basic Scripting Edition. The default language is Visual Basic. ASP.NET code is compiled into intermediate language and then executed by the common language runtime.

If you look at the rest of the source code that's sent to the browser, you'll notice that each of our Web Forms controls is converted to HTML for display in the browser. We drew the text box on the Web Form, but the ASP.NET run-time engine did all the coding for us.

<input name="tbDate" type="text" readonly="readonly"    style="border-style:Outset;height:26px;   width:350px;LEFT: 38px; POSITION: absolute; TOP: 34px" />

For the sake of brevity, I'll show only a portion of the HTML used to generate the calendar. We are several levels of abstraction removed from having to provide all this code ourselves. We can now program a consistent object model of a graphical control, yet the ASP.NET run-time engine will take our graphical calendar control and convert it to HTML 3.2 to ensure that it can be consistently displayed on even older browsers. We can draw a calendar control on our Web Form, and that control is converted to HTML for us. Cool.

<table cellspacing="0" cellpadding="2" bordercolor="White" border="0" style="color:Black; background-color:White;border-color:White;border-width:1px; border-style:solid;font-family:Verdana;font-size:9pt; height:190px;width:350px;border-collapse:collapse;LEFT: 34px; POSITION: absolute; TOP: 72px"> <tr><td colspan="7" style="background-color:White; border-color:Black;border-width:4px;border-style:solid;"> <table cellspacing="0" border="0" style="color:#333399; font-family:Verdana;font-size:12pt;font-weight:bold; width:100%;border-collapse:collapse;"> <tr><td valign="Bottom" style="color:#333333;font-size:8pt; font-weight:bold;width:15%;">



Coding Techniques for Microsoft Visual Basic. NET
Coding Techniques for Microsoft Visual Basic .NET
ISBN: 0735612544
EAN: 2147483647
Year: 2002
Pages: 123
Authors: John Connell

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