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

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

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

80 Chapter 3 • ASP Server Controls

namespace myVbCodeBehind.The complete listing for Figure 3.19 is also available in the CodeBehind.aspx file in the accompanying CD.

<%@ page language="VB" src="vbCb.vb" inherits="myVbCodeBehind.vbCb" %>

1.Develop the page layout in an .aspx file (shown in Figure 3.19). Be sure to include the page directive.

Figure 3.19 The .aspx File for the Code-Behind Example (CodeBehindVB.aspx)

<!— Chapter3\CodeBehindVb.aspx —>

<%@ page language="VB" debug="true" src="vbCb.vb" inherits="myVbCodeBehind.vbCb" %>

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

Select a flower, and click the submit button please: <br> <asp:ListBox id="lstFlowers" runat="server" rows="3"> </asp:ListBox><br><br>

<asp:Button id="btnSubmit" runat="server" text="Submit" onclick="showSelection" /><br><br>

<asp:Label id=lblMessage runat="server" /> </body></form></html>

2.Develop the VB class file (shown in Figure 3.20) and save it in the same directory. In this particular application, we need to import the System and the System.WebUI.WebControls namespaces. Depending on the nature of your applications, you may need to import other namespaces, too.The code for Figure 3.20 is also available in the accompanying CD.

Figure 3.20 The VB Class File for the Code-Behind Example (vbCb.vb)

' Chapter3\vbCb.vb

Option Strict Off

Imports System

Imports System.Web.UI.WebControls

Namespace myVbCodeBehind

Public Class vbCb : Inherits System.Web.UI.Page

Public lstFlowers As System.Web.UI.WebControls.ListBox

Continued

www.syngress.com

ASP Server Controls • Chapter 3

81

Figure 3.20 Continued

Public lblMessage As System.Web.UI.WebControls.Label

Public btnSubmit As System.Web.UI.WebControls.Button

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) If Not IsPostBack Then

lblMessage.Text="No Selection Yet" lstFlowers.Items.Add(new ListItem("Tulip")) lstFlowers.Items.Add(new ListItem("Rose")) lstFlowers.Items.Add(new ListItem("Redbud")) lstFlowers.SelectedIndex=0

End If

End Sub

Protected Sub showSelection(ByVal obj As Object, ByVal e As EventArgs)

lblMessage.Text="You have selected " + _ lstFlowers.SelectedItem.Text

End Sub

End Class

End Namespace

3. Test the ASPX application. It should work fine.

Using Code Behind with Compilation

In this method, you will need to compile your VB or C# source file to a .dll file first.Then copy the .dll file and save it in the bin subdirectory of your virtual directory. Rather than manually copying the .dll file to the bin directory, you may also use the /out parameter of the compilation command to save the .dll file directly to your bin directory, as follows:

G:\MyAspNets\CodeBehind>vbc /out:..\bin\vbCb.dll /t:library vbCb.vb

In the compilation command, we assume that the name of the VB file is vbCb.vb.This command will create the vbCb.dll file in the bin directory directly upon compilation. Now we need to enter a page declarative at the top of our ASPX page as follows. Here, the name of the source file (cs or vb) should be

www.syngress.com

82 Chapter 3 • ASP Server Controls

specified in the Code-Behind attribute.The Inherits attribute should include the namespace.className of the class file:

<%@ page language="VB" codebehind="vbCb.vb"

inherits="myCodeBehind.vbCb" %>

Although we are staging this example using C#, you may change the VB code shown in the previous example very easily to implement this application in VB.The output of this example would appear exactly similar to the one shown in Figure 3.18.

1.Develop the .aspx file (Figure 3.21). Here, we assume that you will develop the C# class in a file named CsharpCodeBehind.cs. We further assume that the name of the class will be cSharpCb in a namespace myCsCodeBehind.Thus, be sure to include the Code-Behind attribute to link the page to the code behind class file as follows.The code shown in Figure 3.21 is also available in the accompanying CD in a file named

CodeBehindCS.aspx.

<%@ page language="cs" debug="true"codebehind="CSharpCodeBehind.cs"

inherits="myCsCodeBehind.cSharpCb" %>

Figure 3.21 Complete Listing (CodeBehindCS.aspx)

<!— Chapter3\CodeBehindCS.aspx —>

<%@ page language="cs" Debug="true" codebehind="CSharpCodeBehind.cs" inherits="myCsCodeBehind.cSharpCb" %>

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

Select a flower, and click the submit button please: <br> <asp:ListBox id="lstFlowers" runat="server" rows="3"> </asp:ListBox><br><br>

<asp:Button id="btnSubmit" runat="server" text="Submit" onclick="showSelection" /><br><br>

<asp:Label id=lblMessage runat="server" /> </body></form></html>

www.syngress.com

ASP Server Controls • Chapter 3

83

2.Develop the Code-Behind class file as shown in Figure 3.22.The code shown in Figure 3.22 is also available in the accompanying CD in a file named CsharpCodeBehindCS.cs.

Figure 3.22 Complete Listing for CSharpCodeBehind.cs

// Chapter\CSharpCodeBehind.cs namespace myCsCodeBehind

{using System;

using System.Web.UI.WebControls;

public class cSharpCb : System.Web.UI.Page

{public System.Web.UI.WebControls.ListBox lstFlowers; public System.Web.UI.WebControls.Label lblMessage; public System.Web.UI.WebControls.Button btnSubmit;

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack)

{lblMessage.Text="No Selection Yet"; lstFlowers.Items.Add(new ListItem("Tulip")); lstFlowers.Items.Add(new ListItem("Redbud"));

lstFlowers.Items.Add(new ListItem("Poppy"));

}

}

protected void showSelection(object obj, EventArgs e) { lblMessage.Text="You have selected " +

lstFlowers.SelectedItem.Text;

}

}

}

3.Compile the class file as follows. Note: If you are using the VB version, just replace the csc keyword with vbc, and change the name of the source file.

csc /t:library /r:System.dll /r:System.Web.dll CSharprpCodeBehind.cs

4.Copy the .dll file in the bin directory of your virtual directory. You are done.

www.syngress.com

84 Chapter 3 • ASP Server Controls

When we develop Web applications using VS.Net, it forces us to implement the code-behind methodology. In the next section we will walk you through the steps for developing a simple application using VS.Net.

Using VS.Net for Developing a Web Application

In this section we will provide a step-by-step procedure to develop a simple Web page using VS.Net. Our finished page will be displayed in the browser as shown in Figure 3.23.

Figure 3.23 The Flower Selection Page Developed Using VS.Net

1.Start a new Visual Basic ASP.NET project as shown in Figure 3.24. Be sure to provide a name for your project.

Figure 3.24 Starting a New VB ASP.NET Web Application

2.After you click OK, the system will display the VS.Net IDE screen. Do not get intimidated by the complex appearance of the screen.With some practice, you will start loving the environment.You will see an empty Web page with two tabs at the bottom: Design and HTML. If the toolbox is not visible, use the View | ToolBox of the system menu to

www.syngress.com

ASP Server Controls • Chapter 3

85

display the toolbox. Click on the Web Forms tab of the toolbox.You will see all of the server controls in the toolbox. Draw a Label. If the

Property Window is not visible, use F4 (or View | Property Window menu) to display the property window of the label. Change its Text property to Select a Flower Please as shown in Figure 3.25. Please note that the system is building the WebForm1.aspx file automatically for you.

Figure 3.25 The VS.Net IDE Screen

3.Draw a ListBox control. Change its ID property and Rows property lstFlower and 3, respectively.You may also change its background Color and Font to your taste. Be sure to set its AutoPostBack property to True. Now double-click on any empty place of the form.The system will bring the code screen as shown in Figure 3.26. Please note that the system has already generated the VB Code-Behind. It has named it WebForm1.aspx.vb. In the Page_Load event, enter the necessary code for loading the list box.

4.You are almost done. Go back to the design view of the WebForm1.aspx. Draw a label at the bottom of the list box, and change its ID property to lblMessage. Now double-click the list box.The system will bring the code screen with the template for the lstFlower_SelectedIndexChanged event procedure. Enter the following code in this event:

lblMessage.Text="You have selected " + _

lstFlowers.SelectedItem.Text

www.syngress.com

86 Chapter 3 • ASP Server Controls

Figure 3.26 Code-Behind Screen in VS.Net

Migrating…

ASP Skills Are Not Obsolete

If you are an experienced ASP developer, your skills are not lost. The new ASP.NET programming model will seem very familiar to you. However, most of your existing ASP pages will have to be modified if you want to run them under ASP.NET. The modifications would be quite simple. Some of the VB Script codes would have to be changed to VB.NET code, and the new ADO.NET would replace your ADO-related codes. In most cases, though, the necessary changes will involve only a few lines of code. You may choose to rewrite existing ASP applications to gain the performance, readability, and maintainability improvements of the new development environment. However, because a Web application can contain both ASP and ASP.NET pages, the conversion does not necessarily have to be carried out all at once.

You are done. Go ahead and test it. Before you test it, you may use the Build menu to build your project (compile the code), and then use the Start icon or Debug | Start of the main menu to run the application. Knowingly or unknowingly, you have developed an ASP.NET Web application.The VS.Net has created a virtual directory in your IIS. If you display the Solution Explorer window,

www.syngress.com

ASP Server Controls • Chapter 3

87

you will see that the VS.Net has done a lot of work for you. By the way, if you look at the HTML code in the WebForm1.aspx file, you will see that VS.Net has styled the list box as follows (only selected attributes are shown):

<asp:ListBox id="lstFlowers" runat="server" Rows="3"

BackColor="#FFE0C0" Font-Bold="True" AutoPostBack="True"

Font-Names="Book Antiqua" Font-Size="Medium" ForeColor="#C04000">

</asp:ListBox>

That means when we develop our .aspx files manually, we can also use these attributes to style our controls.

Using HTML Server Controls

Conventional HTML elements are not programmable at the server side.Their values do not persist in postbacks.These are essentially treated as opaque texts that are passed to the browser. In ASP.NET, we may convert an HTML element to an HTML server control by adding an attribute runat=“server.” This notifies the ASP Engine to create an instance of the control during parsing.We will, of course, need to specify an ID of the element so that we can manipulate it programmatically at the server side.These controls are particularly useful for migrating ASP applications to ASP.NET applications.

HTML server controls have been derived directly or indirectly from the base class System.Web.UI.HtmlControls.HtmlControl and map directly to HTML elements.The hierarchy of HTML server control classes is shown in Figure 3.27. Basically, the hierarchy divides the classes into three major categories: the classes that mimic the HTML <input> tag, the classes that may act as container classes, and finally the HtmlImage class. Several classes in the second category also employ the HTML <input> tag. HTML server controls must reside within a containing <form> control with the runat=“server” attribute.

In this section, we will present a number of examples of HTML server controls. If you are relatively new to ASP, be sure to go through these examples. Most of these examples can also be enhanced using the Web controls. Most importantly, the concepts learned in this section will enable you to develop better applications using Web controls.

www.syngress.com

88 Chapter 3 • ASP Server Controls

Figure 3.27 HTML Server Controls Hierarchy

HtmlInputControl

HtmlInputButton

HtmlInputCheckBox

HtmlInputFile

HtmlInputHidden

HtmlInputImage

HtmlInputRadioButton

HtmlInputText

System.Web.UI.Control

 

HtmlControl

 

HtmlContainerControl

HtmlImage

HtmlAnchor

 

HtmlButton

 

HtmlForm

 

HtmlSelect

 

HtmlTable

 

HtmlTextArea

 

HtmlGenric Control

 

Using the HtmlAnchor Control

You can use the HtmlAchor control (<a>) to navigate from a page to another page.This basically works almost like the Html anchor tag; the only difference is that it works on the server. It has the following attributes:

<a runat="server" id="programmaticID" href= "linkurl"

name="bookmarkname" OnServerClick="onserverclickhandler"

target="linkedcontentframeorwindow" title="titledisplayedbybrowser">

If necessary, we can use this control to dynamically modify the attributes and properties of the <a> element and display hyperlinks from a data source.The href attribute contains the URL of the page to be linked to.We have shown an example of anchor controls in Figure 3.28.

Using the HtmlTable Control

The HtmlTable control mimics the Html <table> tag.We may define rows using <tr> tags.Table cells are defined using <td> tags.This control is a container control, and so we can embed other controls in its cells. It has the following attributes:

www.syngress.com

ASP Server Controls • Chapter 3

89

<table runat="server" id="programmaticID" align=left | center | right

bgcolor="bgcolor" border="borderwidthinpixels"

bordercolor="bordercolor" cellpadding="spacingwithincellsinpixels"

cellspacing="spacingbetweencellsinpixels" height="tableheight"

rows="collectionofrows" width="tablewidth" >

</table>

In the following example, as you can see in Figure 3.28, we will build an HtmlTable with two rows and two columns. Each cell of the table will contain an

HtmlAnchor control.

Figure 3.28 Embedded HTMLAnchor Controls in an HtmlButton Control

The code for this application, as shown in Figure 3.29, is self-explanatory. Each pair of <tr> and </tr> entries enable us to define a row, and within each row, we nest a pair of <td> </td> to define the table’s data (cell). In this example, we have embedded an HtmlAnchor control in each cell.The code shown in Figure 3.29 is available in the accompanying CD in a file named HtmlAnchor1.aspx.

Figure 3.29 HtmlAnchor1.aspx

<!— Chapter3\HtmlAnchor1.aspx —> <html><head></head><form runat="server">

<table style= width: 170px; height: 50px" cellSpacing="0" cellPadding="5" width="170" border="4">

<tr><td><a id="anchor1" runat="server" href="http://www.syngress.com">Syngress Home</a>

</td>

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

Continued

www.syngress.com