Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ASP .NET Web Developer s Guide - Mesbah Ahmed, Chris Garrett

.pdf
Скачиваний:
37
Добавлен:
24.05.2014
Размер:
7.32 Mб
Скачать

90 Chapter 3 • ASP Server Controls

Figure 3.29 Continued

Syngress Catalog</a>

</td>

</tr>

<tr><td><a id="anchor3" runat="server" href="http://www.syngress.com/demo/index.htm"> Syngress Demo </a>

</td>

<td><a id="anchor4" runat="server" href="http://www.syngress.com/specials/index.htm">

Syngress Specials</a> </td>

</tr>

</table></form></html>

Using HtmlInputText and HtmlTextArea Controls

You can use both of these controls to collect text data from the user.You can use the HtmlInputText control to implement server-side code against the HTML

<input type=text> and <input type=password> tags. Its major attributes are these: type (text or password), runat, id, maxlength, size , and value.The HtmlTextArea control enables the user to enter multi-line text.Thus, it is the server-side equivalent to the HTML <textarea> element. Its rows and cols properties can be used to define its size.You can use its onserverchange attribute to run an event handling function.

We will illustrate the usage of these controls with an example. In this application, the user will enter a short story in a text area, and then he or she will enter the name in a textbox, and the password in a password-type textbox. On the click event of a button, we will check the password and display the appropriate message in an html <span> element.The run-time view of the application is shown in Figure 3.30.The code (shown in Figure 3.31) for this application is pretty straightforward and more or less self-explanatory.The code shown in Figure 3.31 is also available in the accompanying CD in a file named HtmlText1.aspx.

www.syngress.com

ASP Server Controls • Chapter 3

91

Figure 3.30 Using HtmlInputText and HtmlTextArea Controls

Figure 3.31 HtmlText1.aspx

<!— Chapter3/HtmlText1.aspx —> <html><form method="post" runat="server"> Your Story:<br>

<TextArea id="txtAreaStory" runat="server" cols="20" rows="3"/><br> Name?<input type="text" id="txtName" size="12" runat="server"/><br> Password? <input type="password" id="txtPwd" runat="server" size="12"/> <br><input type="Button" runat="server" value="Enter"

OnServerClick="CheckPassword"/>

<span id="spnMessage" runat="server"> </span></h2> </form></html>

<script language="VB" runat="server">

Sub checkPassword(source As Object, e As EventArgs)

If txtName.Value="Pepsi" And txtPwd.Value="Beagle" Then spnMessage.InnerHtml="<b>Password Correct: Story Accepted!!</b>"

Else

spnMessage.InnerHtml="<b>Bad Password: Story Rejected!!</b>" End If

End Sub </script>

Using HtmlButton and HtmlImage Controls

You will find two of these controls: HtmlInputButton and HtmlButton. The HtmlInputButton supports the HTML Reset and Submit button types. On the

www.syngress.com

92 Chapter 3 • ASP Server Controls

other hand, the HtmlButton control can be used to develop server-side code against the HTML <button> element.We can provide custom code for the OnServerClick event.You can customize its appearance and imbed other controls in it.We have used HtmlButton controls in many of our previous examples. In our next example, we will embed an HTML <img> element inside a button.We have used the OnMouseOver and OnMouseOut attributes of a button control to provide rollover effects.We have also shown how to use an in-line style attribute that you can use to format many of the controls.The run-time view of the application and its code listing are shown in Figure 3.32 and Figure 3.33, respectively.The relevant code is also available on the accompanying CD in a file named HtmlButton1.aspx.

Figure 3.32 Using the HtmlImage Control in an HtmlButton Control

NOTE

To run this code, you will need to copy the SmallSpinReel1.jpg in the Images folder of your virtual directory.

Figure 3.33 HtmlButton1.aspx

<html><form runat="server">

<h4><font face="Verdana">

HtmlButton Sample With Embedded <img> Tag And Rollover

</font></h4>

<font face="Verdana" size="-1"><p>

<Button id="btnReel"

Continued

www.syngress.com

ASP Server Controls • Chapter 3

93

Figure 3.33 Continued

OnServerClick="btnReel_OnClick"

OnMouseOver="this.style.backgroundColor='yellow'"

OnMouseOut="this.style.backgroundColor='white'"

style="font: 8pt verdana; background-color:lightgreen; border-color:blue; height:100; width:170"

runat="server">

<img src="images/SmallSpinReel1.jpg"/><b> Bass Master!</b> </Button><p>

<Span id=span1 runat="server" /> </font></form></body></html>

<script language="VB" runat="server">

Sub btnReel_OnClick(Source As Object, e As EventArgs) span1.InnerHtml="You clicked Bass Master"

End Sub </script>

Using the HtmlInputFile Control

The HtmlInputFile control has been designed to program against the HTML <input type=file> element.We can use this control to enable users to upload binary or text files from a browser to a directory that we specify in our Web server. Its major attributes are as follows:

<input type=file runat="server" id="programmaticID"

accept="MIMEencodings" maxlength="maxfilepathlength"

size="widthoffilepathtextbox" postedfile="uploadedfile"

>

When this control is rendered, it automatically displays a Browse button for directory browsing. Figure 3.34 illustrates the usage of an HtmlInputFile control. The user may upload a file from his or her machine to our c:\temp directory of the Web server.The code for this application is shown in Figure 3.35 and is available on the CD in a file named HtmlFile1.aspx. As you will observe from this code, we have used the fileControl.PostedFile.SaveAs((“c:\temp\” + targetName.Value)) statement to accomplish the objective.

www.syngress.com

94 Chapter 3 • ASP Server Controls

Figure 3.34 Using the HtmlFile Control for Uploading Files to the Server

Figure 3.35 HtmlFile1.aspx

<!— HtmlFile1.aspx —><html><head></head>

<h3>Using Html File Control</h3>

<form enctype="multipart/form-data" runat="server">

Select a file to upload:

<input type="file" id="fileControl" runat="server"><br> Save as: (Just the name only please):

<input id="txtTargetName" type="text" runat="server"><br> <input type=button id="btnLoad" value="Upload"

OnServerClick="btnLoad_Click" runat="server"><br> <span id=span1 runat="server" /><br>

</form></html>

<script language="VB" runat="server">

Sub btnLoad_Click(s As Object, e As EventArgs)

If txtTargetName.Value="" Then

span1.InnerHtml="Error: you must enter a file name" Return

End If

If Not (fileControl.PostedFile Is Nothing) Then

Try

fileControl.PostedFile.SaveAs(("c:\temp\" + targetName.Value)) span1.InnerHtml="Done: File loaded to <b>c:\temp\" + _ txtTargetName.Value & "</b> on the Web server"

Catch err As Exception

Continued

www.syngress.com

ASP Server Controls • Chapter 3

95

Figure 3.35 Continued

span1.InnerHtml="Error saving file <b>c:\temp\" + _

txtTargetName.Value & "</b><br>" & err.ToString()

End Try

End If

End Sub

</script>

Using the HtmlSelect Control with

Data Binding to a SortedList Structure

The HtmlSelect control has been offered to program against the HTML <select> element. Basically, it enables us to develop a combo box (dropdown list) or a list box. If the size attribute is set to 1, then it behaves like a dropdown list.We may allow the selection of multiple items by using its Multiple property. If we allow multiple selections, we will need to use its Items(i).Selected property to test if its element i has been selected. An HtmlSelect control can be bound to an external data source. Figure 3.36 shows an example of a bound HtmlSelect control.

Figure 3.36 Binding an HtmlSelect Control to a SortedList Object

At first sight, the example will appear to be very simple. However, we have employed a number of common ASP.NET techniques here. Please review the example carefully as it will become very handy when you deal with more challenging applications using Web server controls. Our objective is to bind an HtmlSelect control with a field of a commonly used structure named SortedList. The SortedList structure, like the ArrayList and HashTable, is an offering in the Net SDK Collection Class.We may use a SortedList to store a collection of objects in alphabetic order of a key field. Subsequently, we may retrieve a desired

www.syngress.com

96 Chapter 3 • ASP Server Controls

value either by using array-like addressing or by its key.The complete code for this application is shown in Figure 3.37 (and can also be found in the accompanying CD in a file named HtmlSelect1.aspx).

Figure 3.37 HtmlSelect1.aspx

<!— Chapter3\HtmlSelect1.aspx —>

<%@ page language="VB" debug="true" %>

<html><head></head><form runat="server">

<select id= "lstFlowers" size="3" runat="server" /><br/><br/>

<input id="btnSubmit" type="button" runat="server" value="Submit"

onServerClick="showSelection"><br/><br/>

<span id=spnMessage runat="server"/><br>

<span id=spnPrice runat="server"/><br>

</form></html>

<script language="VB" runat="server">

Sub Page_Load(source As Object, e As EventArgs)

If Not IsPostBack Then

Dim sortedList1 As New SortedList()

' Load the SortedList object

sortedList1.Add("Tulip", 10.75)

sortedList1.Add("Poppy",20.22)

sortedList1.Add("Azalea",30.33)

Dim i As Integer

'Bind the HtmlSelect control (list box) with the key values

'of the SortedList object

lstFlowers.DataSource=sortedList1.Keys

lstFlowers.DataBind()

Session.Timeout=10 'Set the session timeout to 10 minutes ' Save the populated SortedList in the session

Session("savedList")=sortedList1

End If

End Sub

Sub showSelection(sender As Object, e As EventArgs)

Dim sortedList1 As New SortedList()

' Load the Session’s savedList into an instance of a SortedList

Continued

www.syngress.com

ASP Server Controls • Chapter 3

97

Figure 3.37 Continued

sortedList1=Session("savedList")

Dim i As Integer

Dim msg As String

Dim dblPrice as Double dblPrice=sortedList1.GetValueList(lstFlowers.SelectedIndex) spnMessage.InnerHtml="You have selected " + lstFlowers.Value spnPrice.InnerHtml="Its price is: " + FormatCurrency(dblPrice)

End Sub </script>

Creating and Loading the SortedList

In the Page_Load event, we have loaded the SortedList as follows:

Dim sortedList1 As New SortedList()

sortedList1.Add("Tulip", 10.75)

sortedList1.Add("Poppy",20.22)

sortedList1.Add("Azalea",30.33)

By default, the name of a flower (the first parameter) will be loaded in the sorted list as the key-field.The price of the flower (the second parameter) will be stored as its value. After the sorted list object is loaded, we have bound the HtmlSelect control to the key-field of the sorted list as follows:

lstFlowers.DataSource=sortedList1.Keys

lstFlowers.DataBind()

On the click event of the button, our intention is to display the price of the selected flower.Where will we get the price? Obviously, we want to retrieve it from the sorted list object. However, there is a minor problem.Whereas the values of the controls in an ASP.NET page are state-full, the values of the variables are state-less. Hence, on postback, the sorted list would not be available.We may solve this problem in many ways.The easiest way is to load the sorted list again. Placing the relevant code outside the If Not IsPostBack block can do that. But that will cause repetitive loading of the sorted list object on each postback.Therefore, we have instead saved the sorted list in a Session object. Subsequently, we have retrieved the sorted list object from the session variable in the showSelection procedure.The value of the sorted list has been retrieved using its GetValueList method.

www.syngress.com

98 Chapter 3 • ASP Server Controls

Using HtmlCheckBox and

HtmlInputRadioButton Controls

We can use the HtmlInputCheckBox control to develop server-side code against the HTML <input type=checkbox> element.This is done using the Checked property of this control.The HtmlInputRadioButton control can be used to provide server-side programmability to an HTML <input type=radio> element.We can group these controls together by specifying a name property common to all <input type=radio> elements within the group. Only one radio button in a group can be checked at a time. Figure 3.38 shows a simple example of these controls.The complete code is shown in Figure 3.39.The code, shown in Figure 3.39, is self-explanatory and can be found in a file named HtmlInputCheck1.aspx in the accompanying CD.

Figure 3.38 Using HtmlCheckBox and HtmlInputRadioButton Controls

Figure 3.39 HtmlInputCheck1.aspx

<!— Chapter3\HtmlInputCheck1.aspx —> <%@ page language="VB" debug="true" %> <html><head></head><form runat="server"> Select a room type<br>

<input type="radio" id="radOceanFront" name="rgrView" runat="server"/>Ocean Front: $600.00<br>

<input type="radio" id="radOceanView" name="rgrView" runat="server"/>Ocean View: $400.00<br><br>

Select one or more special facilities: <br> <input type="checkbox" id= "chkFishing" runat="server"/> Deep Sea Fishing: $450.00<br>

Continued

www.syngress.com

ASP Server Controls • Chapter 3

99

Figure 3.39 Continued

<input type="checkbox" id= "chkGolf"

runat="server" />Golf at Diamond's Head: $150.00<br>

<input id="btnSubmit" type="button" runat="server" value="Submit" onServerClick="showPrice"><br><br>

<span id=spnPrice runat="server"/><br> </form></html>

<script language="VB" runat="server">

Sub showPrice(sender As Object, e As EventArgs)

Dim totalPrice As Double=0

If radOceanFront.Checked Then totalPrice += 600.00

End If

If radOceanView.Checked Then totalPrice += 400.00

End If

If chkFishing.Checked Then totalPrice += 450.00

End If

If chkGolf.Checked Then totalPrice += 150.00

End If

spnPrice.InnerHtml="Total Price is: " + FormatCurrency(totalPrice) End Sub

</script>

www.syngress.com