Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

Chapter 27 Introducing ASP.NET

575

Understanding Server Controls

The Web forms controls you added to the form are collectively known as Server controls. Server controls are similar to the standard HTML items that you can use on an ordinary Web page except that they are more programmable. Most Server controls expose event handlers, methods, and properties that code running on the server can execute and modify dynamically at run time. In the following exercises, you will learn more about programming Server controls.

Examine a Server control

1.In the Design View window displaying EmployeeForm.aspx, click the Source button.

2.Examine the HTML code for the form. Look at the definition of the first Label control in more detail (the following code has been laid out to make it easier to read):

<asp:Label ID=”Label1” runat=”server” Font-Bold=”True” Font-Names=”Arial Black” Font-Size=”X-Large” Height=”36px”

Text=”Litware, Inc. Software Developers” Width=”630px” Style=”position: absolute; left: 96px; top: 24px”></asp:Label>

There are a couple of things to observe. First, look at the type the control is, asp:Label.

All Web forms controls live in the asp namespace because this is the way they are defined by Microsoft. The second noteworthy item is the runat=”server” attribute. This

attribute indicates that the control can be accessed by code running on the Web server. This code can query and change the values of any of the properties of this control (for example, change its text).

HTML Controls

ASP.NET also supports HTML controls. If you expand the HTML category in the Toolbox, you are presented with a list of controls. These are the controls that Microsoft supplied with the original ASP model. They are provided so that you can port existing ASP pages into ASP.NET more easily. However, if you are building a Web application from scratch, you should use the Standard Web Forms controls instead.

HTML controls also have a runat attribute so that you can specify where event handling code should be executed for these controls. Unlike Web forms controls, the default location for HTML controls to execute code is in the browser rather than on the server— assuming that the user’s browser supports this functionality.

576 Part VI Building Web Applications

The EmployeeForm.aspx page requires you to add the following functionality:

Populate the PositionRole drop-down list when the user selects a position (Worker, Boss, Vice President, President).

Save the information entered when the user clicks the Save button.

Clear the form when the user clicks the Clear button.

You will implement this functionality by writing event handlers.

Note The methods you will add in the following exercise use hard-coded values for the various roles and the jobs that they can perform. In a professional application, you should store this type of information in a database and use a technology such as ADO.NET or DLINQ to retrieve the various roles and their associated jobs from the database. You will see how to use DLINQ with an ASP.NET Web application in Chapter 29.

Handle Server control events

1.In Solution Explorer, expand the file EmployeeForm.aspx.

The file EmployeeForm.aspx.cs will appear. This is the file that will actually contain the C# code for the event handlers that you write. This file is known as a code-behind file. You can separate the C# code from the display logic for a Web application by us-

ing this feature of ASP.NET. (You can actually write C# code and event handlers in the EmployeeForm.aspx file by using the Source View window, but this approach is not recommended.)

2.In the Code and Text Editor window displaying the source view for EmployeeForm.aspx, examine the first line of the file. It contains the following text:

<%@ Page Language=”C#” ... CodeFile=”EmployeeForm.aspx.cs ... %>

The CodeFile directive specifies the file containing the program code for the Web form and the language in which it is written, in this case, C#. The other supported languages include Microsoft Visual Basic and JScript.

3.In Solution Explorer, double-click the EmployeeForm.aspx.cs file.

The file appears in the Code and Text Editor window. At the top of the file, there is a set of using statements. Note that this file makes heavy use of the System.Web namespace

and its subnamespaces—this is where the ASP.NET classes reside. Also, notice that the code itself is in a class called _Default that descends from System.Web.UI.Page; this is

the class from which all Web forms descend. Currently, it contains a single empty method called Page_Load. This method runs when the page is displayed. You can write code in this method to initialize any data required by the form.

Chapter 27 Introducing ASP.NET

577

4. Add a method called initPositionRole to the _Default class after the Page_Load method:

private void initPositionRole()

{

}

You will invoke this method to initialize the positionRole drop-down list to its default set of values.

5. Add the following statements shown in bold type to the initPositionRole method:

private void initPositionRole()

{

positionRole.Items.Clear(); positionRole.Enabled = true; positionRole.Items.Add(“Analyst”); positionRole.Items.Add(“Designer”); positionRole.Items.Add(“Developer”);

}

The first statement clears the items from the drop-down list box. The second statement activates the list box. (You will write some code shortly that disables it under certain circumstances.) The remaining statements add the three roles that are applicable to workers.

6. Add the statements shown here in bold type to the Page_Load method:

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

initPositionRole();

}

}

This block of code causes the positionRole drop-down list to be populated when the form appears in the user’s browser. However, it is important to understand that the Page_Load method runs every time the Web server sends the form to the user’s browser. For example, when the user clicks a button the form can be sent back to the Web server for processing; the Web server then responds by sending the form back to the browser for displaying when the processing has completed. You don’t want the initialization to be performed every time the page appears because it is a waste of process-

ing and can lead to performance problems if you are building a commercial Web site. You can determine whether the Page_Load method is running because this is the first time the page is being displayed by querying the IsPostBack property of the Web page. This property returns false the first time the page is displayed and true if the page is

being redisplayed because the user has clicked a control. In the code you added, you call the initPositionRole method only when the form is first displayed.

578

Part VI Building Web Applications

7.Switch to the EmployeeForm.aspx file, and click the Design button. Select the Worker radio button. In the Properties window toolbar, click the Events toolbar button. (This button has a little lightning icon.) Double-click the CheckedChanged event. This event

occurs when the user clicks the radio button and its value changes. Visual Studio 2008 generates the method workerButton_CheckedChanged to handle this event.

Note The Properties window of an ASP.NET Web application provides additional features not currently available when you build a WPF application. These features include being able to list the events available for a control and specify an event handler. When you create a WPF application, this functionality is available only when you edit the Extensible Application Markup Language (XAML) code for a control.

8.In the Code and Text Editor window, add the statement shown here in bold type to the workerButton_CheckedChanged event method:

protected void workerButton_CheckedChanged(object sender, EventArgs e)

{

initPositionRole();

}

Remember that the default values for the positionRole drop-down list are those for a worker, so the same method can be reused to initialize the list.

9.Switch to the Design View window displaying the EmployeeForm.aspx form. Select the Boss radio button, and use the Properties window to create an event method called bossButton_CheckedChanged for the CheckedChanged event. When the form is displayed in the Code and Text Editor window, type the following statements in the

BossCheckedChanged method:

protected void bossButton_CheckedChanged(object sender, EventArgs e)

{

positionRole.Items.Clear(); positionRole.Enabled = true; positionRole.Items.Add(“General Manager”); positionRole.Items.Add(“Project Manager”);

}

These are the roles that a manager can fulfill.

10.Return to the Design View window displaying the EmployeeForm.aspx form, and create an event handler for the CheckedChanged event for the Vice President radio button. In the Code and Text Editor window, add the following statements shown in bold type to the vpButton_CheckedChanged event method:

protected void vpButton_CheckedChanged(object sender, EventArgs e)

{

positionRole.Items.Clear(); positionRole.Enabled = true;

Chapter 27 Introducing ASP.NET

579

positionRole.Items.Add(“VP Sales”); positionRole.Items.Add(“VP Marketing”); positionRole.Items.Add(“VP Production”); positionRole.Items.Add(“VP Human Resources”);

}

11.Switch to the Design View window displaying the EmployeeForm.aspx form, and create an event handler for the CheckedChanged event for the President radio button. Add the code shown here in bold type to the presidentButton_CheckedChanged event method:

protected void presidentButton_CheckedChanged(object sender, EventArgs e)

{

positionRole.Items.Clear(); positionRole.Enabled = false;

}

Roles do not apply to the president of the company, so the drop-down list is cleared and disabled.

12.Return to the Design View window displaying the EmployeeForm.aspx form, and create an event handler for the Click event of the Save button. The method would usually save

the information to a database, but to keep this application simple, the method will just echo some of the data in the InfoLabel control instead. Add the following statements shown in bold type to the saveButton_Click method:

protected void saveButton_Click(object sender, EventArgs e)

{

String position = “”;

if (workerButton.Checked) position = “Worker”;

if (bossButton.Checked) position = “Manager”;

if (vpButton.Checked)

position = “Vice President”; if (presidentButton.Checked)

position = “President”;

infoLabel.Text = “Employee:&nbsp” + firstName.Text + “&nbsp” + lastName.Text + “&nbsp&nbsp&nbsp&nbspId:&nbsp” + employeeID.Text + “&nbsp&nbsp&nbsp&nbspPosition:&nbsp” + position;

}

The &nbsp character is a nonbreaking space in HTML; ordinary white-space characters after the first white-space character will usually be ignored by the browser.

13.Using the same technique, create an event method for the Click event of the Clear button. Add the following block of code shown in bold type to this method:

protected void clearButton_Click(object sender, EventArgs e)

{

firstName.Text = “”; lastName.Text = “”;

580

Part VI Building Web Applications

employeeID.Text = “”; workerButton.Checked = true; bossButton.Checked = false; vpButton.Checked = false; presidentButton.Checked = false; initPositionRole(); infoLabel.Text = “”;

}

This code clears the information entered by the user and then resets the role to Worker (the default value).

Note Although only one radio button in a group can have its Checked property set to true, it is necessary to set the Checked property of the remaining radio buttons to false to

ensure that the correct button is displayed as being selected when ASP.NET refreshes the form in the user’s Web browser.

Test the Web form again

1.On the Debug menu, click Start Debugging to run the Web form again.

2.When the Web form appears in Internet Explorer, type an employee’s name, enter an ID number (make them up), and then click the Role drop-down list.

The list of roles for a worker is displayed.

3.Change the position of your fictitious employee to Vice President, and then click the Role drop-down list box.

Notice that the list has not changed and still displays the roles for a worker. The list hasn’t changed because the CheckedChanged event for the Vice President radio button has not been raised.

4.Close Internet Explorer, and return to Visual Studio 2008.

5.Display the EmployeeForm.aspx Web form in the Design View window, and then select the worker-Button radio button. In the Properties window, set the AutoPostBack property to True.

Tip If the Properties window is still displaying the list of events for the radio button, click the Properties button next to the Events button on the Properties window toolbar.

Chapter 27 Introducing ASP.NET

581

When the user clicks this radio button, the form will be sent back to the server for processing, the CheckedChanged event will fire, and the form can be updated to display the roles for this radio button. By default, the AutoPostBack property is set to False to

avoid unnecessary network traffic.

6.Set the AutoPostBack property to True for the other radio buttons: bossButton, vpButton, and presidentButton.

7.Run the Web form again.

This time you will find that when you click the radio buttons, there is a slight flicker while the form is submitted to the server, the event handler runs, the drop-down list is populated, and the form is displayed again.

8.On the Internet Explorer toolbar, click the Page drop-down list, and then click View Source to display the source of the HTML page being displayed in the browser.

Note If the Internet Explorer Security message box appears, click Allow so that you can view the source file for the page.

Notepad starts and displays the HTML source for the page. Notice that there is no mention of any “asp:” Server controls in this file and no C# code. Instead, the Server controls and their contents have been converted to the equivalent HTML controls (and some JavaScript). This is one of the basic features of the Server controls—you access them programmatically like ordinary .NET Framework objects, with methods, properties, and events. When they are rendered by the Web server, they are converted to HTML so that you can display the form in any HTML-compliant browser.

9.When you have finished examining the file, close Notepad.

10.On the Web form, click Save.

The InfoLabel control displays the details of the new employee. If you examine the source, you will see that the HTML for the InfoLabel control (rendered as an HTML span with an ID of “InfoLabel”) contains this text.

11.Click Clear.

The form resets to its default values.

12.Close Internet Explorer, and return to Visual Studio 2008.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]