Chapter 3: Creating Our First ASP.NET Web Page
By Scott Mitchell
Writing the Source Code for the ASP.NET Web Page
Now that we have completed the HTML portion of our ASP.NET Web page, all that remains is the source code. The source code will read the user's inputs and perform the necessary calculations to arrive at the monthly cost for the mortgage.
In the previous hour we looked at the Page_Load event handler. This event handler, which you can include in your ASP.NET Web page's source code portion, is executed each time the Web page is loaded. We will not be placing the source code to perform the monthly mortgage cost calculation in this event handler, though, because we do not want to run the calculation until the user has entered the loan amount, interest rate, and duration, and has clicked the Compute Monthly Cost button.
Button Web controls have a Click event, which fires when the button is clicked. Therefore, what we want to do is write our own event handler and associate it with the Compute Monthly Cost button's Click event. This way, whenever the Compute Monthly Cost button is clicked, the event handler that we provide will be executed. All that remains, then, is to place the source code that performs the computation inside this event handler.
Adding event handlers to a Button Web control's Click event is quite easy to accomplish with the Web Matrix Project. From the designer, simply double-click the Button whose Click event you would like to provide an event handler for. Once you double-click the Button Web control, you will be whisked to the Code tab, where you should see the following source code already entered:
Sub performCalc_Click(sender As Object, e As EventArgs) End Sub
These two lines of code are the shell for the button's Click event handler. Note that the event handler is named performCalc_Click. More generally, it is named buttonID_Click, where buttonID is the value of the button's ID property. (Recall that after adding the Button Web control, we changed its ID from Button1 to performCalc.)
Any code that you write between these two lines will be executed whenever the performCalc button is clicked. Because we want to compute the monthly cost of the mortgage when the performCalc button is clicked, the code to perform this calculation will appear within the performCalc_Click event handler.
Reading the Values in the TextBox Web Controls
In order to calculate the monthly cost of the mortgage, we must first be able to determine the values entered by the user into the three TextBox Web controls. Before we look at the code to accomplish this, let's take a step back and reexamine Web controls, a topic we touched upon lightly in the previous hour.
Recall from Hour 2's discussion that when the ASP.NET engine is executing an ASP.NET Web page, Web controls are handled quite differently from standard HTML elements. Standard HTML markup is passed directly from the ASP.NET engine to the Web server without any translation; with Web controls, however, an object is created that represents the Web control. The object is created from the class that corresponds to the specific Web control. That is, a TextBox Web control has an object instantiated from the TextBox class, whereas a Label Web control has an object instantiated from the Label class.
Note - Recall that a class is an abstract blueprint, whereas an object is a concrete instance. When an object is created, it is said to have been instantiated. The act of creating an object is often referred to as instantiation.
Each of these classes has various properties that describe the state of the Web control. For example, the TextBox class has a Size property that indicates how many columns the textbox has. Both the TextBox and the Label classes have Text properties that indicate that Web control's text content.
Tip - The classes that represent various Web controls are classes in the .NET Framework. We will discuss how to find the properties, methods, and events for these classes in future hours.
The primary benefit of Web controls is that their properties can be accessed in the ASP.NET Web page's source code section. Because the Text property of the TextBox Web control contains the content of the textbox, we can reference this property in the Compute Monthly Cost button's Click event handler to determine the value entered by the user into each textbox.
For example, to determine the value entered into the Mortgage Amount textbox, we could use the following line of code:
When the ASP.NET engine creates an object for the Web control, it names the object the value of the Web control's ID property. Because loanAmount is the ID of the Mortgage Amount TextBox Web control, the object created representing this Web control is named loanAmount. To retrieve the Text property of the loanAmount object, we use the syntax loanAmount.Text.
Note - Don't worry if the syntax for retrieving an object's property confuses you. We will be discussing the syntax and semantics of Visual Basic .NET in greater detail in Hour 5, "Visual Basic .NET Variables and Operators."
The Complete Source Code
Listing 3.1 contains the complete source code for our ASP.NET Web page. Take a moment to enter the source code shown below into the performCalc Button's Click event handler. (You should do this from the Code or All tab.)
Tip - Keep in mind that the line numbers shown in Listing 3.1 should not be typed in as well. The line numbers are present in the code listing only to help reference specific lines of the listing when discussing the code.
Listing 3.1 The Computation Is Performed in the performCalc Button's Click Event Handler
1: Sub performCalc_Click(sender As Object, e As EventArgs) 2: 'Specify constant values 3: Const INTEREST_CALCS_PER_YEAR as Integer = 12 4: Const PAYMENTS_PER_YEAR as Integer = 12 5: 6: 'Create variables to hold the values entered by the user 7: Dim P as Double = loanAmount.Text 8: Dim r as Double = rate.Text / 100 9: Dim t as Double = mortgageLength.Text 10: 11: Dim ratePerPeriod as Double 12: ratePerPeriod = r/INTEREST_CALCS_PER_YEAR 13: 14: Dim payPeriods as Integer 15: payPeriods = t * PAYMENTS_PER_YEAR 16: 17: Dim annualRate as Double 18: annualRate = Math.Exp(INTEREST_CALCS_PER_YEAR * Math.Log(1+ratePerPeriod)) - 1 19: 20: Dim intPerPayment as Double 21: -intPerPayment = (Math.Exp(Math.Log(annualRate+1)/payPeriods) - 1) * payPeriods 22: 23: 'Now, compute the total cost of the loan 24: Dim intPerMonth as Double = intPerPayment / PAYMENTS_PER_YEAR 25: 26: Dim costPerMonth as Double 27: costPerMonth = P * intPerMonth/(1-Math.Pow(intPerMonth+1,-payPeriods)) 28: 29: 30: 'Now, display the results in the results Label Web control 31: results.Text = "Your mortgage payment per month is $" & costPerMonth 32: End Sub
An in-depth discussion of the code in Listing 3.1 will have to wait until the next hour. For now, simply enter the code as is, even if there are parts of it you don't understand. One thing to pay attention to, though, is in lines 7 through 9. In these three lines we are reading the values of the three TextBox Web controls and assigning the values to variables.
Note - If the source code in Listing 3.1 has you hopelessly lost and confused, don't worry. The point of this hour is to get you creating a useful ASP.NET Web page quickly; we will take the time needed to dissect the HTML and source code portions of this ASP.NET Web page in the next two hours.
The mathematical equations used to calculate the monthly interest cost can be found at http://www.faqs.org/faqs/sci-math-faq/compoundInterest/. A more in-depth discussion of these formulas can be found at http://people.hofstra.edu/faculty/Stefan_Waner/RealWorld/Summary10.html.