ASP.NET Web Forms


As mentioned earlier, much of the functionality in ASP.NET is achieved using Web Forms. Before long you’ll dive in and create a simple Web Form to give you a starting point to explore this technology. First, however, this section reviews some key points pertinent to Web Form design. It should be noted that some ASP.NET developers simply use a text editor such as Notepad to create files. I wouldn’t advocate this myself, because the benefits you get via an IDE such as Visual Studio 2003 and 2005 or Web Developer Express are substantial, but it’s worth mentioning because it is a possibility. If you do take this route, you have a great deal of flexibility as to which parts of a Web application you put where. This enables you, for example, to combine all your code in one file. You can achieve this by enclosing code in <script> elements, using two attributes on the opening <script> tag:

  <script language="c#" runat="server">    // Server-side code goes here. </script> 

The runat=”server” attribute here is crucial, because it instructs the ASP.NET engine to execute this code on the server rather than sending it to the client, thus giving you access to the rich environment hinted at earlier. You can place your functions, event handlers, and so on, in server-side script blocks.

If you omit the runat=”server” attribute, you are effectively providing client-side code, which will fail if it uses any of the server-side style coding that is discussed in this chapter. You can, however, use <script> elements to supply client-side script in languages such as JavaScript. For example:

  <script language="JavaScript" type="text/JavaScript">    // Client-side code goes here; you can also use "vbscript". </script> 

Tip 

Note that the type attribute here is optional, but necessary if you want XHTML compliance.

It is equally possible to create ASP.NET files in Visual Studio, which is great for you, as you’re already familiar with this environment for C# programming. However, the default project setup for Web applications in this environment has a slightly more complex structure than a single .aspx file. This isn’t a problem for you, though, and does make things a bit more logical (more programmer-like and less Web-developer-like). For this reason, you’ll use Visual Studio throughout this chapter for your ASP.NET programming (instead of Notepad).

The .aspx files can also include code in blocks enclosed by <% and %> tags. However, function definitions and variable declarations cannot go here. Instead, you can insert code that is executed as soon as the block is reached, which is useful when outputting simple HTML content. This behavior is similar to that of old-style ASP pages, with one important difference: the code is compiled, not interpreted. This results in far better performance.

Now it’s time for an example. In Visual Studio you create a new Web application by using the File image from book New image from book Web Site menu option. From the dialog that appears, select the Visual C# language type and the ASP.NET Web Site template. At this point, you have a choice to make. Visual Studio can create Web sites in a number of different locations:

  • On your local IIS Web server

  • On your local disk, configured to use the built-in Visual Web Developer Web server

  • At any location accessible via FTP

  • On a remote Web server that supports Front Page Server Extensions

Without worrying about the latter two choices, which use remote servers, you are left with the first two choices. In general, IIS is the best place to install ASP.NET Web sites, because it is likely to be closest to the configuration required when you deploy a Web site. The alternative, using the built-in Web server, is fine for testing but has certain limitations:

  • Only the local computer can see the Web site.

  • Access to services such as SMTP is restricted.

  • The security model is different from IIS - the application runs in the context of the current user rather than in an ASP.NET-specific account.

This last point requires clarification, because security is very important when it comes to accessing databases or anything else that requires authentication. By default, Web applications running on IIS do so in an account called ASPNET on Windows XP, 2000, and Vista Web servers, or in an account called NETWORK SERVICES on Windows Server 2003. This is configurable if you are using IIS, but not if you use the built-in Web server.

For the purposes of illustration, though, and because you may not have IIS installed on your computer, you can use the built-in Web server. You aren’t worried about security at this stage, so you can go with simplicity.

Create a new ASP.NET Web Site called PCSWebApp1 using the File System option, at C:\ProCSharp\ Chapter32, as shown in Figure 32-2.

image from book
Figure 32-2

After a few moments, Visual Studio .NET should have set up the following:

  • PCSWebApp1, a new solution containing the C# Web Application PCSWebApp1

  • A reserved folder called App_Data for containing data files, such as XML files or database files

  • Default.aspx, the first ASP.NET page in the Web application

  • Default.aspx.cs, a “code-behind” class file for Default.aspx

You can see all of this in the Solution Explorer, as shown in Figure 32-3.

image from book
Figure 32-3

You can view .aspx files in design or source (HTML) view. This is the same as for Windows Forms (as discussed in Part III). The initial view in Visual Studio is either the design or source view for Default .aspx (you can toggle between the views using the buttons in the bottom left). The design view is shown in Figure 32-4.

image from book
Figure 32-4

Underneath the (currently empty) form, you can see where in the HTML for the form the cursor is currently positioned. Here the cursor is in a <div> element inside the <body> element of the page. The source view for the page shows you the code generated inside the .aspx file:

  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"   Inherits="_Default" %> <!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>Untitled Page</title> </head> <body>   <form  runat="server">     <div>     </div>   </form> </body> </html> 

If you know any HTML syntax, this will look familiar to you. You are presented with the basic code required for an HTML page following the XHTML schema, with a few extra bits of code. The most important extra is the <form> element, which will contain your ASP.NET code. The most important thing to note here is the runat attribute. Just as with the server-side code blocks you saw at the start of this section, this is set to server, meaning that the processing of the form will take place on the server. If you don’t include this reference, then no server-side processing will be performed, and the form won’t do anything. There can only be one server-side <form> element in an ASP.NET page.

The other interesting thing about this code is the <%@ Page %> tag at the top. This tag defines page characteristics that are important to you as a C# Web application developer. There is a Language attribute that specifies that you will use C# throughout your page, as you saw earlier with <script> blocks (the default for Web applications is Visual Basic .NET, although this can be changed using a Web.config file, which you’ll see later in this chapter). The other three attributes, AutoEventWireup, CodeFile, and Inherits, are used to associate the Web Form with a class in a code-behind code file, in this case the partial class Default_aspx in the file Default.aspx.cs. This leads straight into a necessary discussion about the ASP.NET code model.

The ASP.NET Code Model

In ASP.NET a combination of layout (HTML) code, ASP.NET controls, and C# code is used to generate the HTML that users see. The layout and ASP.NET code is stored in an .aspx file, such as the one you looked at in the preceding section. The C# code that you add to customize the behavior of the form is contained either in the .aspx file or, as in the preceding example, in a separate .aspx.cs file, which is usually referred to as the “code-behind” file.

When an ASP.NET Web Form is processed - typically when a user requests the page, although sites can be precompiled - several things happen:

  • The ASP.NET process examines the page, and determines what objects must be created in order to instantiate the page object model.

  • A base class for the base is dynamically created, including members for the controls on the page as well as event handlers for these controls (such as button click events).

  • Additional code contained in the .aspx page, as well as any additional code files for the page, is combined with this base class to complete the object model - hence the need for a partial class in the code-behind file, as noted earlier.

  • The complete code is compiled and cached ready to process subsequent requests.

  • HTML is generated and returned to the user.

The code-behind file generated for you in the PCSWebApp1 Web site for Default.aspx is initially very sparse. First, you see the default set of namespace references that you are likely to use in ASP.NET Web pages:

 using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;

Below these references you see an almost completely empty partial class definition for Default_aspx:

  public partial class _Default : System.Web.UI.Page {    protected void Page_Load(object sender, EventArgs e)    {    } } 

Here the Page_Load()event handler can be used to add any code that is required when the page is loaded. As you add more event handlers, and so on, this class file will become increasingly full of code. Note that you don’t see the code that wires up this event handler to the page - this is inferred by the ASP.NET runtime, as noted earlier. This is due to the AutoEventWireUp attribute - setting this to false will mean that you’ll have to associate the event handlers in your code with events on your own.

ASP.NET Server Controls

Your generated code doesn’t do very much yet, so next you need to add some content. You can do this in Visual Studio using the Web Form designer, which supports drag-and-drop in just the same way as the Windows Forms designer.

You can add three types of controls to your ASP.NET pages:

  • HTML server controls - These controls mimic HTML elements, which will be familiar to HTML developers.

  • Web server controls - This is a new set of controls, some of which have the same functionality as HTML controls. These controls have a common naming scheme for properties and other elements to ease development, and provide consistency with analogous Windows Forms controls. There are also some completely new and very powerful controls, as you will see later. Several types of Web server controls exist, including the standard ones such as buttons, validation controls for validating user input, login controls to simplify user management, and more complicated controls for dealing with data sources.

  • Custom and user controls - These controls are defined by the developer and can be created in a number of ways, as discussed in Chapter 33, “ASP.NET Development.”

Tip 

The next section provides a list of many of the frequently used Web server controls, along with usage notes. Some additional controls are examined in the next chapter. HTML controls will not be covered in this book. These controls don’t do anything more than the Web server controls, and the Web server controls provide a richer environment for developers more familiar with programming than with HTML design. Learning how to use the Web server controls provides enough knowledge to use HTML server controls. For more information, check out Professional ASP.NET 2.0 (Wiley Publishing, Inc., ISBN 0-7645-7610-0).

Now you add a couple of Web server controls to the PCSWebApp1 Web site you created in the last section. All Web server controls are used in the following XML element-type form:

 <asp:controlName runat="server" attribute="value">Contents</asp:controlName>

controlName is the name of the ASP.NET server control, attribute=”value” is one or more attribute specifications, and Contents specifies the control content, if any. Some controls allow properties to be set using attributes and control element content, such as Label (used for simple text display), where Text can be specified in either way. Other controls might use an element containment scheme to define their hierarchy, for example Table (which defines a table), which can contain TableRow elements in order to specify table rows declaratively.

Because the syntax for controls is based on XML (although the controls may be used embedded in non-XML code such as HTML), it is an error to omit the closing tags and /> for empty elements, or to overlap controls.

Finally, you once again see the runat=”server” attribute on the Web server controls. It is just as essential here as it is elsewhere, and it is a common mistake to skip this attribute, resulting in Web Forms that don’t function.

This first example is simple. Change the HTML design view for Default.aspx as follows:

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">   <title>Untitled Page</title> </head> <body>   <form  runat="server">     <div>       <asp:Label runat="server"  /><br />       <asp:Button runat="server"  Text="Click Me" />     </div>   </form> </body> </html>

Here you have added two Web Form controls: a label and a button.

Tip 

Note that as you do this, Visual Studio .NET IntelliSense predicts your code entry, just as in the C# code editor.

Going back to the design screen, you can see that your controls have been added, and named using their ID attributes (the ID attribute is often known as the identifier of a control). As with Windows Forms, you have full access to properties, events, and so on through the Properties window and get instant feedback in code or design whenever you make changes.

Any server controls you add will automatically become part of the object model for the form that you are building. This is an instant bonus for Windows Forms developers - the similarities are beginning to emerge!

To make this application do something, you can add an event handler for clicking the button. Here you can either enter a method name in the Properties window for the button or just double-click the button to get the default event handler. If you double-click the button, you’ll automatically add an event-handling method as follows:

  protected void triggerButton_Click(object sender, EventArgs e) { } 

This is hooked up to the button by some code added to the source of Default.aspx:

 <div>   <asp:Label Runat="server"  /><br />   <asp:Button Runat="server"  Text="Click Me"     OnClick="triggerButton_Click" /> </div>

Here the OnClick attribute lets the ASP.NET runtime know to wire up the click event of the button to the triggerButton_Click() method when it generates the code model for the form.

Modify the code in triggerButton_Click() as follows:

 void triggerButton_Click(object sender, EventArgs e) {    resultLabel.Text = "Button clicked!"; }

Now you’re ready to make it go. There is no need to build the project; you simply need to make sure everything is saved and then point a Web browser at the location of the Web site. If you had used IIS this would be simple, because you’d know the URL to point at. However, because you are using the built-in Web server for this example, you need to start things running. The quickest way to do this is to press Ctrl+F5, which will start the server and open a browser pointing at the required URL.

When the built-in Web server is running, an icon will appear in your system tray. If you double-click this icon, you can see what the Web server is doing, and stop it if required. This is shown in Figure 32-5.

image from book
Figure 32-5

In Figure 32-5 you can see the port that the Web server is running on and the URL required to see the Web site you have created.

The browser that has opened should display the Click Me button on a Web page. Before pressing the button, take a quick look at the code received by the browser using View image from book Source (in IE). The <form> section should look something like this:

  <form method="post" action="Default.aspx" >   <div>     <input type="hidden" name="__VIEWSTATE"         value="/wEPDwUKLTE2MjY5MTY1NWRktIU+e0Err8we+94Sk89ncFFD8mY=" />   </div>   <div>     <span ></span><br />     <input type="submit" name="triggerButton" value="Click Me"        />   </div>   <div>     <input type="hidden" name="__EVENTVALIDATION"        value="/wEWAgK2jOKSCwLHpP+yC4UZr3hqCegp5GUi3VsfI+WQ9Rq3" />   </div> </form> 

The Web server controls have generated straight HTML; <span> and <input> for <asp:Label> and <asp:Button>, respectively. There is also a <input type=”hidden”> field with the name VIEWSTATE. This encapsulates the state of the form, as mentioned earlier. This information is used when the form is posted back to the server to re-create the user interface, keeping track of changes and so on. Note that the <form> element has been configured for this; it will post data back to Default.aspx (specified in action) via an HTTP POST operation (specified in method). It has also been assigned the name form1.

After clicking the button and seeing the text appear, check out the source HTML again (spacing has been added for clarity):

 <form method="post" action="Default.aspx" >   <div>     <input type="hidden" name="__VIEWSTATE"        value="/wEPDwUKLTE2MjY5MTY1NQ9kFgICAw9kFgICAQ8PFgIeBFRleHQFD0J1dHRvbiB              jbGlja2VkIWRkZN3zQXZqDnF2ddEBw4Kj7MEqj9pJ" />   </div>   <div>     <span >Button clicked!</span><br />     <input type="submit" name="triggerButton" value="Click Me"        />   </div>   <div>     <input type="hidden" name="__EVENTVALIDATION"        value="/wEWAgLl3MPHAwLHpP+yCwFfz4kBL6+KP1xjB0lgrAagee1y" />   </div> </form>

This time the value of the view state contains more information, because the HTML result relies on more than the default output from the ASP.NET page. In complex forms this can be a very long string indeed, but you shouldn’t complain, because so much is done for you behind the scenes. You can almost forget about state management, keeping field values between posts, and so on. Where the length of the view state string becomes a problem, you can disable view state for controls that do not need to retain state information. You can also do this for entire pages if you want, which can be useful if the page does not ever need to retain state between postbacks to improve performance.

To convince yourself that you don’t have to perform any compilation manually, try changing the text “Button clicked!” in Default.aspx.cs to something else, saving the file, and clicking the button again. The text on the Web page should change appropriately.

The Control Palette

This section takes a quick look at some of the available controls before you put more of them together into a full, and more interesting, application. This section is divided into topics that correspond to the divisions in the toolbox you can see when editing ASP.NET pages, as shown in Figure 32-6.

image from book
Figure 32-6

Note that the control descriptions refer to properties - in all cases, the corresponding attribute for use in ASP.NET code is identically named. Note that this section isn’t an attempt to provide a complete reference, so many controls and properties are omitted. Only the most frequently used controls and properties are shown here. Also, the AJAX Extensions controls won’t be listed here. These controls are part of ASP.NET AJAX, and you will see them in Chapter 34.

Crystal Reports Web Server Controls

These Web server controls enable Crystal Report information to be presented on Web pages. Because this is quite a specialized area, they will not be covered in this book.

Standard Web Server Controls

Almost all the Web server controls (in this and other categories) inherit from System.Web.UI.WebControls .WebControl, which in turn inherits from System.Web.UI.Control. Those that don’t use this inheritance instead derive either directly from Control or from a more specialized base class that derives (eventually) from Control. As a result, the Web server controls have many common properties and events that you can use if required. There are quite a few of these, so I won’t attempt to cover them all, just as with the properties and events of the Web server controls themselves.

Many of the frequently used inherited properties are those that deal with display style. This can be controlled simply, using properties such as ForeColor, BackColor, Font, and so on, but can also be controlled using cascading style sheet (CSS) classes. This is achieved by setting the string property CssClass to the name of a CSS class in a separate file. Other notable properties include Width and Height to size a control, AccessKey and TabIndex to ease user interaction, and Enabled to set whether the control’s functionality is activated in the Web Form.

Some controls can contain other controls, building up a control hierarchy on a page. You can get access to the controls contained by a given control using its Controls property, or to the container of a control via Parent.

You are likely to use the inherited Load event most often, to perform initialization on a control, and PreRender to perform last-minute modifications before HTML is output by the control.

Plenty more events and properties exist, and you see many of these in more detail in the next chapter. In particular, the next chapter deals with more advanced styling and skinning techniques. The following table describes the standard Web server controls in more detail.

Open table as spreadsheet

Control

Description

Label

Simple text display; use the Text property to set and programmatically modify displayed text.

TextBox

Provides a text box that users can edit. Use the Text property to access the entered data, and the TextChanged event to act on selection changes on post- back. If automatic postback is required (as opposed to using a button), set the AutoPostBack property to true.

Button

Adds a standard button for the user to click. Use the Text property for text on the button, and the Click event to respond to clicks (server postback is autom atic). You can also use the Command event to respond to clicks, which gives access to additional CommandName and CommandArgument properties on receipt.

LinkButton

Is identical to Button, but displays button as a hyperlink.

ImageButton

Displays an image that doubles as a clickable button. Properties and events are inherited from Button and Image.

HyperLink

Adds an HTML hyperlink. Set the destination with NavigateUrl and the text to display with Text. You can also use ImageUrl to specify an image for the link and Target to specify the browser window to use. This control has no nonstandard events, so use a LinkButton instead if additional processing is required when the link is followed.

DropDownList

Allows the user to select one of a list of choices, either by choosing it directly from a list or by typing the first letter or two. Use the Items property to set the item list (this is a ListItemCollection class containing ListItem objects) and the SelectedItem and SelectedIndex properties to determine what is selected. The SelectedIndexChanged event can be used to determ ine whether the selection has changed, and this control also has an AutoPostBack property so that this selection change will trigger a postback operation.

ListBox

Allows the user to make one or more selections from a list. Set SelectionMode to Multiple or Single to specify how many items can be selected at once, and Rows to determine how many items to display. Other properties and events are as for DropDownList.

CheckBox

Displays a box that can be checked or unchecked. The state is stored in the Boolean property Checked, and the text associated with the check box in Text. The AutoPostBack property can be used to initiate automatic postback and the CheckedChanged event to act on changes.

CheckBoxList

Creates a group of check boxes. Properties and events are identical to other list controls, such as DropDownList.

RadioButton

Displays a button that can be turned on or off. Generally these are grouped such that only one in the group is active at any time. Use the GroupName property to link RadioButton controls into a group. Other properties and events are as per CheckBox.

RadioButtonList

Creates a group of radio buttons where only one button in the group can be selected at a time. Properties and events are as per other list controls.

Image

Displays an image. Use ImageUrl for the image reference, and AlternateText to provide text if the image fails to load.

ImageMap

Like Image, but allows you to specify specific actions to trigger if users click one or more hotspots in the image. The action to take can either be a postback or a redirection to another URL. Hotspots are supplied by embedded controls that derive from HotSpot, such as RectangleHotSpot and CircleHotSpot.

Table

Specifies a table. Use this in conjunction with TableRow and TableCell at design time, or programmatically assign rows using the Rows property of type TableRowCollection. You can also use this property for runtime modificat ions. This control has several styling properties unique to tables, as do TableRow and TableCell.

BulletedList

Formats a list of items as a bulleted list. Unlike the other list controls, this one has a Click event that you can use to determine what item a user has clicked during a postback. Other properties and events are as for DropDownList.

HiddenField

Used to provide a hidden field, to store nondisplayed values for any reason. These can be very useful to store settings that would otherwise need an alternative stora ge mechanism to function. Use the Value property to access the stored value.

Literal

Performs the same function as Label, but has no styling properties, just a Text one (because it derives from Control, not WebControl).

Calendar

Allows the user to select a date from a graphical calendar display. This control has many style-related properties, but essential functionality can be achieved using the SelectedDate and VisibleDate properties (of type System .DateTime) to get access to the date selected by the user and the month to display (which will always contain VisibleDate). The key event to hook up to is SelectionChanged. Postback from this control is automatic.

AdRotator

Displays several images in succession, with a different one displayed after each server round trip. Use the AdvertisementFile property to specify the XML file describing the possible images, and the AdCreated event to perform processing before each image is sent back. You can also use the Target property to name a window to open when an image is clicked.

FileUpload

This control presents the user with a text box and a Browse button, such that a file to be uploaded can be selected. Once the user has done this, you can look at the HasFile property to determine if a file has been selected, then use the SaveAs() method from code behind to perform the file upload.

Wizard

An advanced control used to simplify the common task of getting several pages of user input in one go. You can add multiple steps to a wizard which can be presented to a user sequentially or nonsequentially, and rely on this control to maintain state and so on.

Xml

A more complicated text display control, used for displaying XML content, which may be transformed using an XSLT style sheet. The XML content is set using one of the Document, DocumentContent, or DocumentSource properties (depending on the format of the original XML), and the XSLT style sheet (optional) using either Transform or TransformSource.

MultiView

A control that contains one or more View controls, where only one View is rendered at a time. The currently displayed view is specified using ActiveViewIndex, and you can detect if the view changes (perhaps due to a Next link on the currently displayed view or similar) using the ActiveViewChanged event.

Panel

Adds a container for other controls. You can use HorizontalAlign and Wrap to specify how the contents are arranged.

PlaceHolder

This control doesn’t render any output, but can be handy for grouping other controls together, or for adding controls programmatically to a given location. Contained controls can be accessed using the Controls property.

View

A container for controls, much like PlaceHolder, but designed for use as a child of MultiView. You can tell if a given View is being displayed using Visible, or use the Activate and Deactivate events to detect changes in activation state.

Substitution

Specifies a section of a Web page that isn’t cached along with other output. This is an advanced topic related to ASP.NET caching behavior, which you won’t be looking at in this book.

Localize

Exactly like Literal, but enables text to be localized by using project resources to specify the text to display for various locales.

Data Web Server Controls

The data Web server controls are divided into two types:

  • Data source controls (SqlDataSource, AccessDataSource, ObjectDataSource, XmlDataSource, and SiteMapDataSource)

  • Data display controls (GridView, DataList, DetailsView, FormView, Repeater, and ReportViewer)

In general, you will place one of the (nonvisual) data source controls on a page to link to a data source; then you’ll add a data display control that binds to a data source control to display that data. Some of the more advanced data display controls, such as GridView, also allow you to edit data.

All the data source controls derive from either System.Web.UI.DataSource or System.Web.UI .HierarchicalDataSource. These classes expose methods such as GetView() (or GetHierarchicalView()) to give access to internal data views and skinning capabilities.

The following table describes the various data source controls. Note that there is less detail about properties in this section than in others - mainly because configuration of these controls is best done graphically or through wizards. Later in this chapter you see some of these controls in action to give you a better understanding about how they work.

Open table as spreadsheet

Control

Description

SqlDataSource

Acts as a conduit for data stored in a SQL Server database. By placing this control on a page, you can manipulate SQL Server data using a data display control. You see this control in action later in the chapter.

AccessDataSource

Like SqlDataSource, but works with data stored in a Microsoft Access database.

ObjectDataSource

This control allows you to manipulate data stored in objects that you have created, which may be grouped in a collection class. This can be a very quick way to expose custom object models to an ASP.NET page.

XmlDataSource

Similar to DataSetDataSource, but works with hierarchical data. This works well in binding to, for example, a TreeView control (one of the Navigation controls). You can also transform XML data using an XSL style sheet using this control if desired.

SiteMapDataSource

Allows binding to hierarchical site map data. See the section on navigation Web server controls later in this chapter for more information.

Next, you have the data display controls, shown in the following table. Several of these are available to suit various needs. Some are more fully functional than others, but often you can go with simplicity (for example, when you don’t need to be able to edit data items).

Open table as spreadsheet

Control

Description

GridView

Displays multiple data items (such as rows in a database) in the form of rows, where each row has columns reflecting data fields. By manipulating the properties of this control, you can select, sort, and edit data items.

DataList

Displays multiple data items where you can supply templates for each item to display data fields in any way you choose. As with GridView, you can select, sort, and edit data items.

DetailsView

Displays a single data item in tabular form, with each row of the table relating to a data field. This control enables you to add, edit, and delete data items.

FormView

Displays a single data item using a template. As with DetailsView, this control enables you to add, edit, and delete data items.

Repeater

Like DataList, but without selecting or editing capabilities.

ReportViewer

An advanced control for displaying reporting services data, that we won’t be looking at in this book.

Validation Web Server Controls

Validation controls provide a method of validating user input without (in most cases) writing any code at all. Whenever postback is initiated, each validation control checks the control it is validating and changes its IsValid property accordingly. If this property is false, the user input for the validated control has failed validation. The page containing all the controls also has an IsValid property - if any of the validation controls has its version of this property set to false, this will be false also. You can check this property from your server-side code and act on it.

Validation controls also have another function. Not only do they validate controls at runtime; they can also output helpful hints to users. Simply setting the ErrorMessage property to the text you want means users will see it when they attempt to post back invalid data.

The text stored in ErrorMessage may be output at the point where the validation control is located, or at a separate point, along with the messages from all other validation controls on a page. This latter behavior is achieved using the ValidationSummary control, which displays all error messages along with additional text as required.

On browsers that support it, these controls even generate client-side JavaScript functions to streamline their validation behavior. This means that in some cases postback won’t even occur, because the validation controls can prevent this under certain circumstances and output error messages without involving the server.

All validation controls inherit from BaseValidator, and thus share several important properties. Perhaps the most important is the ErrorMessage property discussed earlier, with the ControlToValidate property coming in a close second. This property specifies the programmatic ID of the control that is being validated. Another important property is Display, which determines whether to place text at the validation summary position (if set to none), or at the validator position. You also have the choice to make space for the error message even when it’s not being displayed (set Display to Static) or to dynamically allocate space when required, which might shift page contents around slightly (set Display to Dynamic). The following table describes the validation controls.

Open table as spreadsheet

Control

Description

RequiredFieldValidator

Used to check if the user has entered data in a control such as TextBox.

CompareValidator

Used to check that data entered fulfills simple requirements, by use of an operator set using the Operator property and a ValueToCompare property to validate against. Operator can be Equal, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, NotEqual, and DataTypeCheck. DataTypeCheck simply compares the data type of ValueToCompare with the data in the control to be validated. ValueToCompare is a string property but is interpreted as different data types based on its contents. To further control the comparison to make, you can set the Type property to Currency, Date, Double, Integer, or String.

RangeValidator

Validates that data in the control falls between MaximumValue and MinimumValue property values. Has a Type property as per CompareValidator.

RegularExpressionValidator

Validates the contents of a field based on a regular expression stored in ValidationExpression. This can be useful for known sequences such as zip codes, phone numbers, IP numbers, and so on.

CustomValidator

Used to validate data in a control using a custom function. ClientValidationFunction is used to specify a client-side function used to validate a control (which means, unfortunately, that you can’t use C#). This function should return a Boolean value indicating whether validation was successful. Alternatively, you can use the ServerValidate event to specify a server-side function to use for validation. This function is a bool type event handler that receives a string containing the data to validate, instead of an EventArgs parameter. Returns true if validation succeeds, otherwise false.

ValidationSummary

Displays validation errors for all validation controls that have an ErrorMessage set. The display can be formatted by setting the DisplayMode (BulletList, List, or SingleParagraph) and HeaderText properties. The display can be disabled by setting Show Summary to false, and displayed in a pop-up message box by setting ShowMessageBox to true.

Navigation and Login Web Server Controls

These Web server controls are examined in Chapter 33.

WebParts Web Server Controls

These Web server controls enable users to customize page layout as they use your sites. They can choose content regions from a list of available controls, position them on pages, and customize their layout. These controls are covered in Chapter 33.

Server Control Example

In this example, you create the framework for a Web application, a meeting room booking tool. (As with the other examples in this book, you can download the sample application and code from the Wrox Web site at www.wrox.com.) At first you will include only the front end and simple event processing; later you extend this example with ADO.NET and data binding to include server-side business logic.

The Web Form you are going to create contains fields for user name, event name, meeting room, and attendees, along with a calendar to select a date (you’re assuming for the purposes of this example that you are dealing with all-day events). You will include validation controls for all fields except the calendar, which you will validate on the server side, and provide a default date in case none has been entered.

For user interface (UI) testing, you will also have a Label control on the form that you can use to display submission results.

For starters, create a new Web site in Visual Studio .NET in the C:\ProCSharp\Chapter32\ directory, and call it PCSWebApp2. Next, design the form, which is generated using the following code in Default.aspx (with auto-generated code not highlighted):

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"   Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">   <title>Meeting Room Booker</title> </head> <body>   <form  runat="server">     <div>       <h1 style="text-align: center;">         Enter details and set a day to initiate an event.       </h1>     </div> 

After the title of the page (which is enclosed in HTML <h1> tags to get large, title-style text), the main body of the form is enclosed in an HTML <table>. You could use a Web server control table, but this introduces unnecessary complexity because you are using a table purely for formatting the display, not to be a dynamic UI element (an important point to bear in mind when designing Web Forms - don’t add Web server controls unnecessarily). The table is divided into three columns: the first column holds simple text labels; the second column holds UI fields corresponding to the text labels (along with validation controls for these); and the third column contains a calendar control for date selection, which spans four rows. The fifth row contains a submission button spanning all columns, and the sixth row contains a ValidationSummary control to display error messages, when required (all the other validation controls have Display=”None”, because they will use this summary for display). Beneath the table is a simple label that you can use to display results for now, before you add database access later:

  <div style="text-align: center;">   <table style="text-align: left; border-color: #000000; border-width: 2px;     background-color: #fff99e;" cellspacing="0" cellpadding="8" rules="none"     width="540">     <tr>       <td valign="top">         Your Name:</td>       <td valign="top">         <asp:TextBox  Runat="server" Width="160px" />         <asp:RequiredFieldValidator  Runat="server"           ErrorMessage="You must enter a name."           ControlToValidate="nameBox" Display="None" />       </td>       <td valign="middle" rowspan="4">         <asp:Calendar  Runat="server" BackColor="White" />       </td>     </tr>     <tr>       <td valign="top">         Event Name:</td>       <td valign="top">         <asp:TextBox  Runat="server" Width="160px" />         <asp:RequiredFieldValidator  Runat="server"           ErrorMessage="You must enter an event name."           ControlToValidate="eventBox" Display="None" />       </td>     </tr> 

Most of the ASP.NET code in this file is remarkably simple, and much can be learned simply by reading through it. Of particular note in this code is the way in which list items are attached to the controls for selecting a meeting room and multiple attendees for the event:

  <tr>   <td valign="top">     Meeting Room:</td>   <td valign="top">     <asp:DropDownList  Runat="server" Width="160px">       <asp:ListItem Value="1">The Happy Room</asp:ListItem>       <asp:ListItem Value="2">The Angry Room</asp:ListItem>       <asp:ListItem Value="3">The Depressing        Room</asp:ListItem>       <asp:ListItem Value="4">The Funked Out        Room</asp:ListItem>     </asp:DropDownList>     <asp:RequiredFieldValidator  Runat="server"       ErrorMessage="You must select a room."       ControlToValidate="roomList" Display="None" />   </td>   </tr> <tr>   <td valign="top">     Attendees:</td>   <td valign="top">     <asp:ListBox  Runat="server" Width="160px"       SelectionMode="Multiple" Rows="6">       <asp:ListItem Value="1">Bill Gates</asp:ListItem>       <asp:ListItem Value="2">Monica Lewinsky</asp:ListItem>       <asp:ListItem Value="3">Vincent Price</asp:ListItem>       <asp:ListItem Value="4">Vlad the Impaler</asp:ListItem>       <asp:ListItem Value="5">Iggy Pop</asp:ListItem>       <asp:ListItem Value="6">William        Shakespeare</asp:ListItem>     </asp:ListBox> 

Here you are associating ListItem objects with the two Web server controls. These objects are not Web server controls in their own right (they simply inherit from System.Object), which is why you don’t need to use Runat=”server” on them. When the page is processed, the <asp:ListItem> entries are used to create ListItem objects, which are added to the Items collection of their parent list control. This makes it easier for you to initialize lists than to write code for this yourself (you’d have to create a ListItemCollection object, add ListItem objects, and then pass the collection to the list control). Of course, you can still do all of this programmatically if you want.

              <asp:RequiredFieldValidator  Runat="server"               ErrorMessage="You must have at least one attendee."               ControlToValidate="attendeeList" Display="None" />           </td>         </tr>         <tr>           <td align="center" colspan="3">             <asp:Button  Runat="server" Width="100%"               Text="Submit meeting room request" />           </td>         </tr>         <tr>           <td align="center" colspan="3">             <asp:ValidationSummary  Runat="server"               HeaderText="Before submitting your request:" />           </td>         </tr>       </table>     </div>     <div>       <p>         Results:         <asp:Label Runat="server"  Text="None." />       </p>     </div>   </form> </body> </html>

In design view, the form you have created looks like Figure 32-7. This is a fully functioning UI, which maintains its own state between server requests, and validates user input. Considering the brevity of the preceding code, this is quite something. In fact, it leaves you with very little to do, at least for this example; you just have to specify the button click event for the submission button.

image from book
Figure 32-7

Actually, that’s not quite true. So far, you have no validation for the calendar control. All you have to do is give it an initial value. You can do this in the Page_Load() event handler for your page in the code-behind file:

 private void Page_Load(object sender, EventArgs e) {    if (!this.IsPostBack)    {       calendar.SelectedDate = System.DateTime.Now;    } }

Here you just select today’s date as a starting point. Note that you first check to see if Page_Load() is being called as the result of a postback operation, by checking the IsPostBack property of the page. If a postback is in progress, this property will be true and you leave the selected date alone (you don’t want to lose the user’s selection, after all).

To add the button click handler, simply double-click the button and add the following code:

 private void submitButton_Click(object sender, EventArgs e) {    if (this.IsValid)    {       resultLabel.Text = roomList.SelectedItem.Text +          " has been booked on " +          calendar.SelectedDate.ToLongDateString() +          " by " + nameBox.Text + " for " +         eventBox.Text + " event. ";       foreach (ListItem attendee in attendeeList.Items)       {          if (attendee.Selected)          {             resultLabel.Text += attendee.Text + ", ";          }       }       resultLabel.Text += " and " + nameBox.Text +          " will be attending.";    } }

Here you just set the resultLabel control Text property to a result string, which will then appear below the main table. In IE the result of such a submission might look something like Figure 32-8, unless there are errors, in which case the ValidationSummary will activate instead, as shown in Figure 32-9.

image from book
Figure 32-8

image from book
Figure 32-9




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net