- Web Application Primer
- The Web Forms Programming Model
- Code-Behind Programming
- Web Forms and Visual Studio .NET
- A Glimpse into the Future
Web Forms and Visual Studio .NET
Now that you know what makes Web forms tick, it's time to learn to build Web forms the Visual Studio .NET way. Visual Studio .NET brings rapid application development to the Web. You design forms by choosing controls from a palette and dropping them onto forms. You write event handlers by double-clicking controls and filling in empty method bodies. And you compile and run your application by executing simple menu commands. It's no accident that building Web forms with Visual Studio .NET feels a lot like building Windows applications with Visual Basic. That's exactly the feel Microsoft intended to convey.
This article closes with a step-by-step tutorial describing how to build a Web-based mortgage payment calculator with Visual Studio .NET. Figure 8 shows the finished product. Enter a loan amount, interest rate, and term (length of the loan in months), and click the Compute Payment button. The corresponding monthly payment appears at the bottom of the page.
Figure 8 Web-based mortgage payment calculator.
Step 1: Create a Virtual Directory
When you create a Web application project with Visual Studio .NET, you don't tell Visual Studio .NET where to the store the files by entering a path name; you enter a URL. Assuming that you want to store the files on your PC but don't want to clutter \Inetpub\wwwroot with project subdirectories, your first step is to create a project directory and turn it into a virtual directory so that it's URL-addressable. Here are the steps:
Create a folder named Projects somewhere on your hard disk to hold your Web application projects. Then create a Projects subdirectory named LoanCalc.
Start the Internet Information Services applet in Windows. You'll find it under All Programs/Administrative Tools.
In the left pane of the Internet Information Services window, expand the Local Computer\Web Sites folder, and select Default Web Site.
Select the New/Virtual Directory command from the Action menu to start the Virtual Directory Creation Wizard.
When the wizard asks for an alias, type LoanCalc. When it asks for a path name, enter the path to the LoanCalc directory you created in step 1. Click the Next and Finish buttons until the wizard closes.
You just created a physical directory named LoanCalc and converted it into a virtual directory. Its URL is http://localhost/loancalc. Before proceeding, verify that LoanCalc appears with the other virtual directories listed under Default Web Site in the Internet Information Services window, as shown in Figure 9.
Figure 9 Internet Information Services window.
Step 2: Create a Web Application Project
Start Visual Studio .NET, and then select the File/New/Project command. Fill in the New Project dialog box exactly as shown in Figure 10. Verify that the statement "Project will be created at http://localhost/LoanCalc" appears near the bottom of the dialog box. Then click OK to create a new project named LoanCalc in the LoanCalc directory you created a moment ago.
Figure 10 Creating the LoanCalc project.
Step 3: Change to Flow Layout Mode
The next screen you see is the Visual Studio .NET Web forms designer. Here you design forms by dragging and dropping controls. Before you begin, however, you have a decision to make.
The forms designer supports two layout modes: grid layout and flow layout. Grid layout mode lets you place controls anywhere in a form. It relies on CSS-P (Cascading Style SheetsPosition) to achieve precise positioning of controls and other HTML elements. Flow layout mode eschews CSS-P and relies on the normal rules of HTML layout. Flow layout mode is more restrictive, but it's compatible with all contemporary browsers.
So that LoanCalc will be compatible with as wide a range of browsers as possible, go to Visual Studio .NET's Properties window and change to flow layout mode by changing the document's pageLayout property from GridLayout, which is the default, to FlowLayout. Note that DOCUMENT must be selected in the combo box at the top of the Properties window for the pageLayout property to appear.
Before proceeding, click the form and select the Snap to Grid command from Visual Studio .NET's Format menu. This setting will make it easier to size and position the form's controls consistently with respect to one another.
Step 4: Add a Table
Because you're working in flow layout mode, tables are your best friend when it comes to positioning and aligning controls on a page. Click the Web form design window to set the focus to the designer. Then use Visual Studio .NET's Table/Insert/Table command to add an HTML table to the Web form. When the Insert Table dialog box appears, fill it in as shown in Figure 11. In particular, set Rows to 4, Columns to 8, Width to 100 percent, Border Size to 0, and Cell Padding to 8. When you click OK, the table appears in the forms designer window.
Figure 11 Adding a table to a Web form.
Step 5: Insert Text
Click the cell in the table's upper-left corner. A caret appears signaling that any text you type will appear inside the table cell. Type Principal. Then go to the Properties window and change the cell's align property to right, to right-align the text. Repeat the process to add Rate (percent) to the cell in the next row and Term (months) to the cell below that. Figure 12 shows how the table should look when you've finished.
Figure 12 The LoanCalc form after adding text.
Step 6: Add TextBox Controls
If the Toolbox window isn't displayed somewhere in the Visual Studio .NET window (it appears at the far left, by default), choose the Toolbox command from the View menu to display it. Click the Toolbox's Web Forms button to display a list of Web controls, and then use drag-and-drop to add TextBox controls to the cells to the right in the table's first three rows. (See Figure 13.) Finish up by using the Properties window to change the TextBox controls' IDs to Principal, Rate, and Term, respectively.
Figure 13 The LoanCalc form after adding TextBox controls.
Step 7: Add a Button Control
Add a Button control to the rightmost cell in the table's bottom row, as shown in Figure 14. Size the button so that its width equals that of the textbox above it. Change the button text to Compute Payment and the button ID to PaymentButton.
Figure 14 The LoanCalc form after adding a Button control.
Step 8: Add a Label Control
Select a Label control from the Toolbox, and add it to the form just below the table, as shown in Figure 15. Change the Label control's text to an empty string and its ID to Output.
Figure 15 The LoanCalc form after adding a Label control.
Step 9: Edit the HTML
The next step is to dress up the form by adding a few HTML elements. Start by clicking the HTML button at the bottom of the designer window to view the HTML generated for this Web form. Manually add the following statements between the <body> tag and the <form> tag:
<h1> Mortgage Payment Calculator </h1> <hr>
Next scroll to the bottom of the file and add these statements between the </table> tag and the <asp:Label> tag:
<br> <hr> <br> <h3>
Finish up by inserting an </h3> tag after the </asp:Label> tag. Then click the Design button at the bottom of the forms designer to switch out of HTML view and back to design view. Figure 16 shows how the modified form should look.
Figure 16 The LoanCalc form after adding HTML tags.
Step 10: Add a Click Handler
Double-click the form's Compute Payment button. Visual Studio .NET responds by adding a method named PaymentButton_Click to WebForm1.aspx.cs and showing the method in the program editor. Add the following code to the empty method body:
try { double principal = Convert.ToDouble (Principal.Text); double rate = Convert.ToDouble (Rate.Text) / 100; double term = Convert.ToDouble (Term.Text); double tmp = System.Math.Pow (1 + (rate / 12), term); double payment = principal * (((rate / 12) * tmp) / (tmp - 1)); Output.Text = "Monthly Payment = " + payment.ToString ("c"); } catch (Exception) { Output.Text = "Error"; }
PaymentButton_Click isn't an ordinary method; it's an event handler. Check out the InitializeComponent method that Visual Studio .NET wrote into WebForm1.aspx.cs, and you'll find a statement that registers PaymentButton_Click to be called in response to the Compute Payment button's Click events. InitializeComponent is called by OnInit. The handler that you just implemented responds to Click events by extracting user input from the form's TextBox controls, computing the corresponding monthly payment, and displaying the result in the Label control.
Step 11: Build and Test
You're now ready to try out your handiwork. Select Build from the Build menu to compile your code. If it builds without errors, choose Start (or Start Without Debugging) from the Debug menu to run it. When the Web form pops up in Internet Explorer, verify that it works properly by entering the following three inputs:
- Principal: 100000
- Rate: 10
- Term: 240
Now click the Compute Payment button. If "Monthly Payment = $965.02" appears at the bottom of the page, give yourself a pat on the back. You just built your first Web form with Visual Studio .NET.
The LoanCalc Source Code
Of the many files in the LoanCalc directory, WebForm1.aspx (see Listing 10) and WebForm1.aspx.cs (see Listing 11) are the two that interest us the most. They contain LoanCalc's source code. WebForm1.aspx contains no code, only HTML. Visual Studio .NET always uses code-behind in its Web forms, so all the C# code is located in WebForm1.aspx.cs. Listings 10 and 11 show the finished versions of both files. Most of the content that you see was generated by Visual Studio .NET. The statements that you added are shown in bold type.
Given what you already know about Web forms, there isn't much in LoanCalc's source code to write home about. The ASPX file defines the user interface using a mixture of HTML and Web controls, and the CS file contains the Compute Payment button's Click handler as well as the code that connects the button to the handler. Neither file contains anything you couldn't have written by hand, but it should be apparent that building Web forms visually is faster and less error-prone than building them manually.
Listing 10: The LoanCalc Source Code: WebForm1.aspx
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="LoanCalc.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body> <h1> Mortgage Payment Calculator </h1> <hr> <form id="Form1" method="post" runat="server"> <TABLE id="Table1" cellSpacing="1" cellPadding="8" width="100%" bgColor="thistle" border="0"> <TR> <TD align="right"> Principal </TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD> <asp:TextBox id="Principal" runat="server"></asp:TextBox> </TD> </TR> <TR> <TD align="right"> Rate (percent) </TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD> <asp:TextBox id="Rate" runat="server"></asp:TextBox> </TD> </TR> <TR> <TD align="right"> Term (months) </TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD> <asp:TextBox id="Term" runat="server"></asp:TextBox> </TD> </TR> <TR> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD></TD> <TD> <asp:Button id="PaymentButton" runat="server" Text="Compute Payment" Width="157px"></asp:Button> </TD> </TR> </TABLE> <br> <hr> <br> <h3> <asp:Label id="Output" runat="server"></asp:Label> </h3> </form> </body> </HTML>
Listing 11: The LoanCalc Source Code: WebForm1.aspx.cs
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace LoanCalc { /// <summary> /// Summary description for WebForm1. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.TextBox Principal; protected System.Web.UI.WebControls.TextBox Rate; protected System.Web.UI.WebControls.Button PaymentButton; protected System.Web.UI.WebControls.Label Output; protected System.Web.UI.WebControls.TextBox Term; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET // Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.PaymentButton.Click += new System.EventHandler(this.PaymentButton_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void PaymentButton_Click(object sender, System.EventArgs e) { try { double principal = Convert.ToDouble (Principal.Text); double rate = Convert.ToDouble (Rate.Text) / 100; double term = Convert.ToDouble (Term.Text); double tmp = System.Math.Pow (1 + (rate / 12), term); double payment = principal * (((rate / 12) * tmp) / (tmp - 1)); Output.Text = "Monthly Payment = " + payment.ToString ("c"); } catch (Exception) { Output.Text = "Error"; } } } }