Chapter 21. Programming ASP.NET Applications

Developers are writing more and more of their applications to run over the Web and to be seen in a browser. As we saw in Chapter 20, Silverlight lets you write C# code to run on the client side in the web browser. As for the server side of a web application, the .NET Framework offers ASP.NET.

The focus of this chapter is to illustrate where ASP.NET and C# programming intersect when using Web Forms. ASP.NET is a huge topic, and for intensive coverage of ASP.NET, please see either Programming ASP.NET 3.5, Fourth Edition by Jesse Liberty, Dan Maharry, and Dan Hurwitz, or Learning ASP.NET 3.5, Second Edition by Jesse Liberty, Dan Hurwitz, and Brian MacDonald (both published by O’Reilly).

Web Forms Fundamentals

Web Forms brings Rapid Application Development (RAD) to the creation of web applications. From within Visual Studio or Visual Web Developer, you drag-and-drop controls onto a form and write the supporting code in code-behind pages. The application is deployed to a web server (typically IIS, which is shipped with most versions of Windows, and Cassini, which is built into Visual Studio for testing your application), and users interact with the application through a standard browser.

Note

ASP.NET supports other models besides Web Forms. You can work directly at the HTTP level, for example. And .NET 4 introduces a new model called MVC (which stands for Model View Controller). MVC is more complex, but is ultimately more powerful and flexible, making it a good choice for more complex web applications. Since this is not an ASP.NET-specific book, we will look only at the simpler, RAD-based Web Forms model.

Web Forms offers a programming model in which web pages are dynamically generated on a web server for delivery to a browser over the Internet. With Web Forms, you can create an ASPX page consisting of HTML and web controls, and you write C# code to respond to user actions and add additional dynamic content. The C# code runs on the server, and the data your code produces is integrated with the controls on your page to create an HTML page that is sent to the browser.

You should pick up the following three critical points from the preceding paragraph and keep them in mind for this entire chapter:

  • Web pages can have both HTML and web controls (described later).

  • ASP.NET processing happens on the server in managed code. (You can, of course, use ASP.NET in conjunction with AJAX or Silverlight if you want client-side code.)

  • ASP.NET controls produce standard HTML for the browser.

A web form divides the user interface into two parts: the visual part or user interface (UI), and the logic that lies behind it. This is called code separation; and it is a good thing.

The UI for an ASP.NET page is stored in a file with the extension .aspx. When you run the form, the server generates HTML that it sends to the client browser. This code uses the rich Web Forms types found in the System.Web and System.Web.UI namespaces of the .NET FCL.

With Visual Studio, Web Forms programming couldn’t be simpler: open a form, drag some controls onto it, and write the code to handle events. Presto! You’ve written a web application.

On the other hand, even with Visual Studio, writing a robust and complete web application can be a daunting task. Web forms offer a very rich UI; the number and complexity of web controls have greatly multiplied in recent years, and user expectations about the look and feel of web applications have risen accordingly.

In addition, web applications are inherently distributed. Typically, the client will not be in the same building as the server. For most web applications, you must take network latency, bandwidth, and network server performance into account when creating the UI; a round trip from client to host might take a few seconds.

Note

To simplify this discussion, and to keep the focus on C#, we’ll ignore client-side processing for the rest of this chapter, and focus on server-side ASP.NET controls.

Web Forms Events

Web forms are event-driven. An event represents the idea that “something happened” (see Chapter 5 for a full discussion of events).

An event is raised when the user clicks a button, or selects from a listbox, or otherwise interacts with the UI. Of course, in web applications these user interactions happen on the client’s machine in the web browser, but ASP.NET events are handled on the server. For this to work, user interactions require a round trip—the browser needs to send a message to the server, and the server needs to respond to handle the event completely. This can take a while, so our hands are somewhat tied compared to classic Windows application event handling—it’s just not practical for ASP.NET to offer server-side event handlers for things like mouse move events. So ASP.NET offers only a limited set of events, such as button clicks and text changes. These are events that the user might expect to cause a significant change, and for which it’s reasonable to perform a round trip to the server.

Postback versus nonpostback events

Postback events are those that cause the form to be posted back to the server immediately. These include click-type events, such as the button Click event. In contrast, many events are considered nonpostback, meaning that the form isn’t posted back to the server immediately.

Note

You can force controls with nonpostback events to behave in a postback manner by setting their AutoPostBack property to true.

Nonpostback events are raised at the point at which ASP.NET discovers it needs to raise them, which may be some considerable time after the user performed the actions to which the events relate. For example, the TextBox web control has a TextChanged event. You wouldn’t expect a web page to submit a form automatically the moment you typed into a text box, and so this is a nonpostback event. If the user fills in several text fields in a form, the server knows nothing about that—this change in state happens on the client side, and it’s only when the user clicks a button to submit the form that ASP.NET discovers the changes. So this is when it will raise TextChanged events for all the text boxes that changed. Consequently, you can expect to see multiple events during the handling of a single submission.

View state

Users tend to expect controls in user interfaces to remember their state—it’s disconcerting when text boxes lose their content, or listboxes forget which item was selected. Sadly, the Web is inherently a “stateless” environment.[58] This means that every post to the server loses the state from previous posts, unless the developer takes great pains to preserve this session knowledge. The Web is rife with sites where you fill in a form, only for it to lose all of your data if anything goes wrong. Developers have to do a lot of extra work to prevent this. ASP.NET, however, provides support for maintaining some of the state automatically.

Whenever a web form is posted to the server, the server re-creates it from scratch before it is returned to the browser. ASP.NET provides a mechanism that automatically maintains state for server controls (ViewState). Thus, if you provide a list and the user has made a selection, that selection is preserved after the page is posted back to the server and redrawn on the client.

Web Forms Life Cycle

Every request for a page made to a web server causes a chain of events at the server. These events, from beginning to end, constitute the life cycle of the page and all its components. The life cycle begins with a request for the page, which causes the server to load it. When the request is complete, the page is unloaded. From one end of the life cycle to the other, the goal is to render appropriate HTML output back to the requesting browser.

Note

Since ASP.NET is a server-side technology, its view of the lifetime of the page is quite different from the user’s view. By the time the user sees the page, the server has already finished with it. Once the HTML has reached the browser, you can switch off and unplug the web server and the user will be none the wiser for as long as she’s looking at that page.

The life cycle of a page is marked by the following events. ASP.NET performs specific processing at each stage, but you can attach handlers to any of these events to perform additional work:

Initialize

Initialize is the first phase in the life cycle for any page or control. It is here that any settings needed for the duration of the incoming request are initialized.

Load ViewState

The ViewState property is populated. The ViewState lives in a hidden input tag in the HTML—when ASP.NET first renders a page, it generates this field, and uses it to persist the state across round trips to the server. The input string from this hidden variable is parsed by the page framework, and the ViewState property is set. This allows ASP.NET to manage the state of your control across page loads so that each control isn’t reset to its default state each time the page is posted.

Process Postback Data

During this phase, the data sent to the server in the posting is processed.

Load

CreateChildControls() is called, which creates and initializes server controls in the control tree. State is restored, and the form controls contain client-side data.

Send Postback Change Modifications

If there are any state changes between the current state and the previous state, change events are raised via the RaisePostDataChangedEvent() method.

Handle Postback Events

The client-side event that caused the postback is handled.

PreRender

This is your last chance to modify control properties prior to rendering. (In web forms, “rendering” means generating the HTML that will eventually be sent to the browser.)

Save State

Near the beginning of the life cycle, the persisted view state was loaded from the hidden variable. Now it is saved back to the hidden variable, persisting as a string object that will complete the round trip to the client.

Render

This is where the output to be sent back to the client browser is generated.

Dispose

This is the last phase of the life cycle. It gives you an opportunity to do any final cleanup and release references to any expensive resources, such as database connections.

Creating a Web Application

Visual Studio offers two ways to build ASP.NET applications. This isn’t just a case of two different menu items for the same feature—the two options work quite differently in ways Visual Studio doesn’t make especially obvious at the point where you make the decision. You can use the New Project dialog, which offers various ASP.NET project templates under the Visual C#Web section, which produce various kinds of web application projects. Alternatively, you can choose FileNewWeb Site from the main menu, and this lets you create various kinds of website projects. Web application projects are fully fledged Visual Studio projects that are built in much the same way as other kinds of projects such as libraries, console applications, or WPF applications. Website projects are somewhat more lightweight—there’s no .csproj file to represent the project, nor do you need to build the project; your project consists of nothing but source files and you end up copying these to the web server. For this chapter, we’ll use a web application project because it’s the most similar to all the other project types we’ve looked at in this book.

To create the simple web form that we will use in the next example, start up Visual Studio .NET and select FileNewProject. In the New Project dialog, select the Visual C#Web templates and choose ASP.NET Empty Web Application from the templates.

As the template name suggests, Visual Studio creates a web application with no pages. It contains a Web.config file to hold website configuration settings, but nothing else. To add a web form, select ProjectAdd New Item and choose Visual C#Web from the templates list on the left. Select the Web Form template, and call it HelloWeb.aspx. Visual Studio creates a HelloWeb.aspx.cs code-behind file as part of the web form, which you can see by expanding the HelloWeb.aspx file in the Solution Explorer. (You’ll also see a HelloWeb.aspx.designer.cs file which is where Visual Studio puts any code it needs to generate automatically. Don’t put any of your own code in there, because Visual Studio deletes and rebuilds that file anytime it needs to change the generated code.)

Code-Behind Files

Let’s take a closer look at the .aspx and code-behind files that Visual Studio created. Look at the HTML view of HelloWeb.aspx. (When you edit an .aspx file, Visual Studio can show three different views. The default view is the “Source” view, which shows the raw HTML. There are three buttons at the bottom left of the editor that let you switch between a “Design” view, which shows the content with the layout and design it will have in the browser, the “Source” view, which shows the raw HTML, or a “Split” view which shows both.) You can see that a form has been specified in the body of the page using the standard HTML form tag:

<form id="form1" runat="server">

ASP.NET web forms require you to have at least one form element to manage the user interaction, so Visual Studio creates one when you add a new .aspx page. The attribute runat="server" is the key to the server-side magic. Any tag that includes this attribute is considered a server-side control to be executed by the ASP.NET Framework on the server.

Note

Although the form tag is standard HTML, the runat attribute is not. But ASP.NET removes that attribute from the page before sending it to the browser. The attribute only has any meaning on the server side.

Within the form, Visual Studio provides an opening and closing pair of div tags to give you somewhere to put your controls and text.

Having created an empty web form, the first thing you might want to do is add some text to the page. By switching to the Source view, you can add script and HTML directly to the file. For example, we can add content to the div element in the body segment of the .aspx page, as the highlighted line in Example 21-1 shows.

Example 21-1. Adding HTML content

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="HelloWeb.aspx.cs"
Inherits="ProgrammingCSharpWeb.HelloWeb" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      Hello World! It is now <%= DateTime.Now.ToString() %>
    </div>
    </form>
</body>
</html>

This will cause it to display a greeting and the current local time:

Hello World! It is now 4/4/2010 5:24:16 PM

The <% and %> marks work just as they did in classic ASP, indicating that code falls between them (in this case, C#). The = sign immediately following the opening tag causes ASP.NET to evaluate the expression inside the tags and display the value. Run the page by pressing F5.

Adding Controls

You can add server-side controls to a web form in three ways: by writing markup in the .aspx page, by dragging controls from the toolbox (to either the Source or Design view), or by writing code that adds them at runtime. For example, suppose you want to use radio buttons to let the user choose one of three shipping companies when placing an order. You can write the following HTML into the <form> element in the HTML window:

<asp:RadioButton GroupName="Shipper" id="Speedy"
    text="Speedy Express" Checked="True" runat="server">
</asp:RadioButton>
<asp:RadioButton GroupName="Shipper" id="United"
    text="United Package" runat="server">
</asp:RadioButton>
<asp:RadioButton GroupName="Shipper" id="Federal"
    text="Federal Shipping" runat="server">
</asp:RadioButton>

The asp tags declare server-side ASP.NET controls that are replaced with normal HTML when the server processes the page. When you run the application, the browser displays three radio buttons in a button group; selecting one deselects the others.

You can create the same effect more easily by dragging three buttons from the Visual Studio toolbox onto the form, or to make life even easier, you can drag a radio button list onto the form, which will manage a set of radio buttons as a group. When you select a radio button list control in the Design view, a smart tag appears, prompting you to choose a data source (which allows you to bind to a collection; perhaps one you’ve obtained from a database) or to edit items. Clicking Edit Items opens the ListItem Collection Editor, where you can add three radio buttons.

Each radio button is given the default name ListItem, but you may edit its text and value in the ListItem properties, where you can also decide which of the radio buttons is selected, as shown in Figure 21-1.

List item collection

Figure 21-1. List item collection

You can improve the look of your radio button list by changing properties in the Properties window, including the font, colors, number of columns, repeat direction (vertical is the default), and so forth, as well as by utilizing Visual Studio’s extensive support for CSS styling, as shown in Figure 21-2.

In Figure 21-2, you can just see that in the lower-righthand corner you can switch between the Properties window and the Styles window. Here, we’ve used the Properties window to set the tool tip, and the Styles window to create and apply the ListBox style, which creates the border around our listbox and sets the font and font color. We’re also using the split screen option to look at Design and Source at the same time.

Using properties and styles

Figure 21-2. Using properties and styles

The tag indications (provided automatically at the bottom of the window) show us our location in the document; specifically, inside a ListItem, within the ListBox which is inside a div which itself is inside form1. Very nice.

Server Controls

Web Forms offers two types of server-side controls. The first is server-side HTML controls. These look like normal HTML controls, but with the extra attribute runat="server".

The alternative to marking HTML controls as server-side controls is to use ASP.NET Server Controls, also called web controls. Web controls have been designed to provide a more convenient server-side API for working with standard HTML controls. Web controls provide a more consistent object model and more consistently named attributes. For example, with HTML controls, there are myriad ways to handle input:

<input type="radio">
<input type="checkbox">
<input type="button">
<input type="text">
<textarea>

Each behaves differently and takes different attributes. This is the unfortunate upshot of the rather haphazard way in which HTML evolved in the early days of the Web. The web controls try to normalize the set of controls, using attributes consistently throughout the web control object model. Here are the web controls that correspond to the preceding HTML server-side controls:

<asp:RadioButton>
<asp:CheckBox>
<asp:Button>
<asp:TextBox rows="1">
<asp:TextBox rows="5">

The HTML that ASP.NET actually serves to the web browser does not contain these tags beginning with asp: which is just as well, because no browser would know what to make of them. It converts them all into standard HTML, so from a client-side perspective, there’s no difference between these ASP.NET web controls and HTML controls. It’s purely a matter of what API you’d like to use on the server side: do you want your server-side code to work with the same element types and property names as you will see on the client, or would you prefer your controls to use the same conventions as all the other .NET classes you use?

The remainder of this chapter focuses on web controls.

Data Binding

While some of the content in a web application may be fixed, any interesting website will change over time. So it’s highly likely that you’ll want some of the controls on your web page to display data that can change from time to time, and which is probably stored in a database. Many ASP.NET controls can be data-bound, which simplifies display and modification of data.

In the preceding section we hardcoded radio buttons onto a form—one for each of three shippers. That can’t be the best way to do it—relationships with suppliers change, and there’s a good chance that we may want to work with different shippers in the future. We don’t really want to have to go back and rewire the controls each time that kind of business relationship changes. It makes more sense to store the list of shippers in a database, and have the UI reflect that. (In fact, if you’re familiar with Microsoft’s sample databases, you may recognize the three shippers in the earlier examples as the ones provided in the “Northwind” sample database.) This section shows you how you can create these controls dynamically and then bind them to data in the database, by using the RadioButtonList control’s data binding support.

Add a new web form called DisplayShippers.aspx to your project. Put the editor into Split mode. From the toolbox, drag a RadioButtonList onto the new form, either onto the design pane or within the <div> in the Source view.

Note

If you don’t see the radio buttons on the left of your work space, try clicking on ViewToolbox to open the toolbox, and then expanding the Standard tab of the toolbox. Right-click on any control in the toolbox, and choose Sort Items Alphabetically.

In the Design pane, click on the new control’s smart tag—the little arrow that appears at the top right of the control. Then, select Choose Data Source and the Data Source Configuration dialog opens, as shown in Figure 21-3.

Data Source Configuration dialog

Figure 21-3. Data Source Configuration dialog

Drop down the “Select a data source” menu and choose <New Data Source>. You are then prompted to choose a data source from the datatypes on your machine. Select Database, assign it an ID, and click OK. The Configure Data Source dialog box opens, as shown in Figure 21-4.

You can either choose an existing connection, or in this case, choose New Connection to configure a new data source, and the Add Connection dialog opens.

Choosing a data connection

Figure 21-4. Choosing a data connection

Fill in the fields: choose your server name, how you want to log in to the server (if in doubt, choose Windows Authentication), and the name of the database (for this example, Northwind). Be sure to click Test Connection to test the connection. When everything is working, click OK, as shown in Figure 21-5.

After you click OK, the connection properties will be filled in for the Configure Data Source dialog. Review them, and if they are OK, click Next. On the next wizard page, name your connection (e.g., NorthWindConnectionString) if you want to save it to your web.config file.

When you click Next, you’ll have the opportunity to specify the tables and columns you want to retrieve, or to specify a custom SQL statement or stored procedure for retrieving the data.

Open the Table list, and scroll down to Shippers. Select the ShipperID and CompanyName fields, as shown in Figure 21-6.

The Add Connection dialog

Figure 21-5. The Add Connection dialog

Click Next, and test your query to see that you are getting back the values you expected, as shown in Figure 21-7.

It is now time to attach the data source you’ve just built to the RadioButtonList. A RadioButtonList (like most lists) distinguishes between the value to display (e.g., the name of the delivery service) and the value of that selection (e.g., the delivery service ID). Set these fields in the wizard, using the drop down, as shown in Figure 21-8.

Configuring the Select statement

Figure 21-6. Configuring the Select statement

Testing the query

Figure 21-7. Testing the query

Binding radio buttons to the data source

Figure 21-8. Binding radio buttons to the data source

Examining the Code

Before moving on, there are a few things to notice. When you press F5 to run this application, it appears in a web browser, and the radio buttons come up as expected. Choose ViewSource, and you’ll see that what is being sent to the browser is simple HTML, as shown in Example 21-2.

Example 21-2. HTML Source view

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/
xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
    <form method="post" action="DisplayShippers.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
value="/wEPDwUJMjMzNjY1MzU4D2QWAgIDD2QWAgIBDxAPFgIeC18hRGF0YUJvdW5kZ2QQFQMOU3BlZWR5
IEV4cHJlc3MOVW5pdGVkIFBhY2thZ2UQRmVkZXJhbCBTaGlwcGluZxUDATEBMgEzFCsDA2dnZ2RkZCOksd8
IILjpH4OAdNkxGqjSa0RYAA3N2F8zJz4lyxsv" />
</div>

<div class="aspNetHidden">

    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" 
    value="/wEWBQK02+CfAgL444i9AQL544i9AQL644i9AQL3jKLTDWylFXks1YMe8G5o7AkyHjJysQk0
    Cliwu8U/2yTrYA/Y" />
</div>
    <div>
        <table id="RadioButtonList1">
    <tr>
        <td><input id="RadioButtonList1_0" type="radio" 
            name="RadioButtonList1" value="1" />
            <label for="RadioButtonList1_0">Speedy Express</label></td>
    </tr><tr>
        <td><input id="RadioButtonList1_1" type="radio" 
            name="RadioButtonList1" value="2" />
            <label for="RadioButtonList1_1">United Package</label></td>
    </tr><tr>
        <td><input id="RadioButtonList1_2" type="radio" 
            name="RadioButtonList1" value="3" />
            <label for="RadioButtonList1_2">Federal Shipping</label></td>
    </tr>
</table>

    </div>
    </form>
</body>
</html>

Notice that the HTML has no RadioButtonList; it has a table, with cells, within which are standard HTML input objects and labels. ASP.NET has translated the developer controls to HTML understandable by any browser.

Warning

A malicious user may create a message that looks like a valid post from your form, but in which he has set a value for a field you never provided in your form. This may enable him to choose an option not properly available (e.g., a Premier-customer option), or even to launch a SQL injection attack. You want to be especially careful about exposing important data such as primary keys in your HTML, and take care that what you receive from the user may not be restricted to what you provide in your form. For more information on secure coding in .NET, see http://msdn.microsoft.com/security/.

Adding Controls and Events

By adding just a few more controls, you can create a complete form with which users can interact. You will do this by adding a more appropriate greeting (“Welcome to NorthWind”), a text box to accept the name of the user, two new buttons (Order and Cancel), and text that provides feedback to the user. Figure 21-9 shows the finished form.

The completed shipper form

Figure 21-9. The completed shipper form

This form won’t win any awards for design, but its use will illustrate a number of key points about Web Forms.

Note

I’ve never known a developer who didn’t think he could design a perfectly fine UI. At the same time, I never knew one who actually could. UI design is one of those skills (such as teaching) that we all think we possess, but only a few very talented folks are good at it. As developers, we know our limitations: we write the code, and someone else lays it out on the page and ensures that usability issues are reviewed. For more on this, I highly recommend every programmer read Don’t Make Me Think: A Common Sense Approach to Web Usability by Steve Krug (New Riders Press) and Why Software Sucks...and What You Can Do About It by David Platt (Addison-Wesley).

Example 21-3 is the complete .aspx file.

Example 21-3. The .aspx file

<%@ Page Language="C#" AutoEventWireup="true"
 CodeBehind="DisplayShippers.aspx.cs"
 Inherits="ProgrammingCSharpWeb.DisplayShippers" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>Welcome to NorthWind</div>
  <div>
    Your name:
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox></div>
    <div>Shipper:</div>
  <div>
    <asp:RadioButtonList ID="rblShippers" runat="server"
       DataSourceID="SqlDataSource1" DataTextField="CompanyName"
       DataValueField="ShipperID">
    </asp:RadioButtonList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
       ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
       SelectCommand="SELECT [ShipperID], [CompanyName] FROM [Shippers]">
    </asp:SqlDataSource>
  </div>
  <div>
    <asp:Button ID="btnOrder" runat="server" Text="Order" />
    <asp:Button ID="Button2" runat="server" Text="Cancel" />
  </div>
  <div>
     <asp:Label id="lblMsg" runat=server></asp:Label>
  </div>
  </form>
</body>
</html>

When the user clicks the Order button, you’ll read the value that the user has typed in the Name text box, and you’ll also provide feedback on which shipper was chosen. Remember, at design time, you can’t know the name of the shipper, because this is obtained from the database at runtime, but we can ask the RadioButtonList for the chosen name or ID.

To accomplish all of this, switch to Design mode, and double-click the Order button. Visual Studio will put you in the code-behind page, and will create an event handler for the button’s Click event.

Note

To simplify this code, we will not validate that the user has entered a name in the text box. For more on the controls that make such validation simple, please see Programming ASP.NET.

You add the event-handling code, setting the text of the label to pick up the text from the text box, and the text and value from the RadioButtonList:

protected void btnOrder_Click(object sender, EventArgs e)
{
    lblMsg.Text = "Thank you " + txtName.Text.Trim() +
        ". You chose " + rblShippers.SelectedItem.Text +
        " whose ID is " + rblShippers.SelectedValue;
}

When you run this program, you’ll notice that none of the radio buttons are selected. Binding the list did not specify which one is the default. There are a number of ways to do this, but the easiest is to add a single line in the Page_Load method that Visual Studio created:

protected void Page_Load(object sender, EventArgs e)
{
    rblShippers.SelectedIndex = 0;
}

This sets the RadioButtonList’s first radio button to Selected. The problem with this solution is subtle. If you run the application, you’ll see that the first button is selected, but if you choose the second (or third) button and click OK, you’ll find that the first button is reset. You can’t seem to choose any but the first selection. This is because each time the page is loaded, the OnLoad event is run, and in that event handler you are (re)setting the selected index.

The fact is that you only want to set this button the first time the page is selected, not when it is posted back to the browser as a result of the OK button being clicked.

To solve this, wrap the setting in an if statement that tests whether the page has been posted back:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        rblShippers.SelectedIndex = 0;
    }
}

When you run the page, the IsPostBack property is checked. The first time the page is posted, this value is false, and the radio button is set. If you click a radio button and then click OK, the page is sent to the server for processing (where the btnOrder_Click handler is run), and then the page is posted back to the user. This time, the IsPostBack property is true, and thus the code within the if statement isn’t run, and the user’s choice is preserved, as shown in Figure 21-10.

Example 21-4 shows the complete code-behind form.

Example 21-4. Code-behind form for DisplayShippers aspx.cs

using System;

namespace ProgrammingCSharpWeb
{
    public partial class DisplayShippers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                rblShippers.SelectedIndex = 0;
            }
        }

        protected void btnOrder_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "Thank you " + txtName.Text.Trim() +
                ". You chose " + rblShippers.SelectedItem.Text +
                " whose ID is " + rblShippers.SelectedValue;
        }
    }
}
The user’s choices preserved on postback

Figure 21-10. The user’s choices preserved on postback

Summary

In this chapter, we saw how to create a simple ASP.NET web application using Web Forms. We bound a list of radio buttons to a database table, and added server-side event handlers that respond to a user’s interaction with a web page.



[58] There are good architectural reasons for this, but it’s bad for usability.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset