Chapter 20. ASP.NET Web Forms

WHAT'S IN THIS CHAPTER?

  • The differences between Web Site and Web Application projects

  • Using the HTML and CSS design tools to control the layout of your web pages

  • Easily generating highly functional web applications with the server-side web controls

  • Adding rich client-side interactions to your web pages with JavaScript and ASP.NET AJAX

When Microsoft released the first version of ASP.NET, one of the most talked-about features was the capability to create a full-blown web application in the same way as you would create a Windows application. The abstractions provided by ASP.NET coupled with the rich tooling support in Visual Studio allowed programmers to quickly develop feature-rich applications that ran over the Web in a wholly integrated way.

ASP.NET version 2.0, which was released in 2005, was a major upgrade that included new features such as a provider model for everything from menu navigation to user authentication, more than 50 new server controls, a web portal framework, and built-in web site administration, to name but a few. These enhancements made it even easier to build complex web applications in less time.

Most of the new features in the latest version of ASP.NET and Visual Studio have focused on improving the client-side development experience. These include enhancements to the HTML Designer and CSS editing tools, better IntelliSense support for JavaScript, HTML and JavaScript snippets, and new project templates.

In this chapter you learn how to create ASP.NET Web Applications in Visual Studio 2010, as well as look at many of the features and components that Microsoft has included to make your web development life a little (and in some cases a lot) easier.

WEB APPLICATION VS. WEB SITE PROJECTS

With the release of Visual Studio 2005, a radically new type of project was introduced — the Web Site project. Much of the rationale behind the move to a new project type was based on the premise that web sites, and web developers for that matter, are fundamentally different from other types of applications (and developers), and would therefore benefit from a different model. Although Microsoft did a good job extolling the virtues of this new project type, many developers found it difficult to work with, and clearly expressed their displeasure to Microsoft.

Fortunately, Microsoft listened to this feedback, and a short while later released a free add-on download to Visual Studio that provided support for a new Web Application project type. It was also included with Service Pack 1 of Visual Studio 2005.

The major differences between the two project types are fairly significant. The most fundamental change is that a Web Site project does not contain a Visual Studio project file (.csproj or .vbproj), whereas a Web Application project does. As a result, there is no central file that contains a list of all the files in a Web Site project. Instead, the Visual Studio solution file contains a reference to the root folder of the Web Site project, and the content and layout are directly inferred from its files and subfolders. If you copy a new file into a subfolder of a Web Site project using Windows Explorer, then that file, by definition, belongs to the project. In a Web Application project you must explicitly add all files to the project from within Visual Studio.

The other major difference is in the way the projects are compiled. Web Application projects are compiled in much the same way as any other project under Visual Studio. The code is compiled into a single assembly that is stored in the in directory of the web application. As with all other Visual Studio projects, you can control the build through the property pages, name the output assembly, and add pre- and post-build action rules.

On the contrary, in a Web Site project all the classes that aren't code-behind-a-page or user control are compiled into one common assembly. Pages and user controls are then compiled dynamically as needed into a set of separate assemblies.

The big advantage of more granular assemblies is that the entire web site does not need to be rebuilt every time a page is changed. Instead, only those assemblies that have changes (or have a down-level dependency) are recompiled, which can save a significant amount of time, depending on your preferred method of development.

Microsoft has pledged that it will continue to support both the Web Site and Web Application project types in all future versions of Visual Studio.

So which project type should you use? The official position from Microsoft is "it depends," which is certainly a pragmatic, although not particularly useful, position to take. All scenarios are different, and you should always carefully weigh each alternative in the context of your requirements and environment. However, the anecdotal evidence that has emerged from the .NET developer community over the past few years, and the experience of the authors, is that in most cases the Web Application project type is the best choice.

Note

Unless you are developing a very large web project with hundreds of pages, it is actually not too difficult to migrate from a Web Site project to a Web Application project and vice versa. So don't get too hung up on this decision. Pick one project type and migrate it later if you run into difficulties.

CREATING WEB PROJECTS

In addition to the standard ASP.NET Web Application and Web Site projects, Visual Studio 2010 provides support and templates for several specialized web application scenarios. These include web services, WCF services, server control libraries, and reporting applications. However, before we discuss these you should understand how to create the standard project types.

Creating a Web Site Project

As mentioned previously, creating a Web Site project in Visual Studio 2010 is slightly different from creating a regular Windows-type project. With normal Windows applications and services, you pick the type of project, name the solution, and click OK. Each language has its own set of project templates and you have no real options when you create the project. Web Site project development is different because you can create the development project in different locations, from the local file system to a variety of FTP and HTTP locations that are defined in your system setup, including the local Internet Information Services (IIS) server or remote FTP folders.

Because of this major difference in creating these projects, Microsoft has separated out the Web Site project templates into their own command and dialog. Selecting New Web Site from the File

Creating a Web Site Project
Figure 20-1

Figure 20-1. Figure 20-1

Most likely, you'll select the ASP.NET Web Site project template. This creates a web site populated with a starter web application that will ensure you your initial application is structured in a logical manner. The template will create a project that demonstrates how to use a master page, menus, the account management controls, CSS, and the jQuery JavaScript library.

In addition to the ASP.NET Web Site project template, there is an Empty Web Site project template that creates nothing more than an empty folder and a reference in a solution file. The remaining templates, which are for the most part variations on the Web Site template, are discussed later in this chapter. Regardless of which type of web project you're creating, the lower section of the dialog enables you to choose where to create the project.

By default, Visual Studio expects you to develop the web site or service locally, using the normal file system. The default location is under the My Documents/Visual Studio 2010/WebSites folder for the current user, but you can change this by overtyping the value, selecting an alternative location from the drop-down list, or clicking the Browse button.

The Location drop-down list also contains HTTP and FTP as options. Selecting HTTP or FTP changes the value in the filename textbox to a blank http:// or ftp:// prefix ready for you to type in the destination URL. You can either type in a valid location or click the Browse button to change the intended location of the project.

The Choose Location dialog (shown in Figure 20-2) is shown when you click the Browse button and enables you to specify where the project should be stored. Note that this isn't necessarily where the project will be deployed, because you can specify a different destination for that when you're ready to ship, so don't expect that you are specifying the ultimate destination here.

The File System option enables you to browse through the folder structure known to the system, including the My Network Places folders, and gives you the option to create subfolders where you need them. This is the easiest way of specifying where you want the web project files, and the way that makes the files easiest to locate later.

Figure 20-2

Figure 20-2. Figure 20-2

Note

Although you can specify where to create the project files, by default the solution file is created in a new folder under the My Documents/Visual Studio 2010/Projects folder for the current user. You can move the solution file to a folder of your choice without affecting the projects.

If you are using a local IIS server to debug your Web Site project, you can select the File System option and browse to your wwwroot folder to create the web site. However, a much better option is to use the local IIS location type and drill down to your preferred location under the Default Web Site folders. This interface enables you to browse virtual directory entries that point to web sites that are not physically located within the wwwroot folder structure, but are actually aliases to elsewhere in the file system or network. You can create your application in a new Web Application folder or create a new virtual directory entry in which you browse to the physical file location and specify an alias to appear in the web site list.

The FTP site location type is shown in Figure 20-2, which gives you the option to log in to a remote FTP site anonymously or with a specified user. When you click Open, Visual Studio saves the FTP settings for when you create the project, so be aware that it won't test whether the settings are correct until it attempts to create the project files and save them to the specified destination.

Note

You can save your project files to any FTP server to which you have access, even if that FTP site doesn't have .NET installed. However, you will not be able to run the files without .NET, so you will only be able to use such a site as a file store.

The last location type is a remote site, which enables you to connect to a remote server that has FrontPage extensions installed on it. If you have such a site, you can simply specify where you want the new project to be saved, and Visual Studio 2010 will confirm that it can create the folder through the FrontPage extensions.

Once you've chosen the intended location for your project, clicking OK tells Visual Studio 2010 to create the project files and store them in the desired location. After the web application has finished initializing, Visual Studio opens the Default.aspx page and populates the Toolbox with the components available to you for web development.

The Web Site project has only a small subset of the project configuration options available under the property pages of other project types, as shown in Figure 20-3. To access these options, right-click the project and select Property Pages.

Figure 20-3

Figure 20-3. Figure 20-3

The References property page, shown in Figure 20-3, enables you to define references to external assemblies or web services. If you add a binary reference to an assembly that is not in the Global Assembly Cache (GAC), the assembly is copied to the in folder of your web project along with a .refresh file, which is a small text file that contains the path to the original location of the assembly. Every time the web site is built, Visual Studio compares the current version of the assembly in the in folder with the version in the original location and, if necessary, updates it. If you have a large number of external references, this can slow the compile time considerably. Therefore, it is recommended that you delete the associated .refresh file for any assembly references that are unlikely to change frequently.

The Build, Accessibility, and Start Options property pages provide some control over how the web site is built and launched during debugging. The accessibility validation options are discussed later in this chapter and the rest of the settings on those property pages are reasonably self-explanatory.

The MSBuild Options property page provides a couple of interesting advanced options for web applications. If you uncheck the Allow This Precompiled Site to be Updatable option, all the content of the .aspx and .ascx pages is compiled into the assembly along with the code-behind. This can be useful if you want to protect the user interface of a web site from being modified. Finally, the Use Fixed Naming and Single Page Assemblies option specifies that each page be compiled into a separate assembly rather than the default, which is an assembly per folder.

The Silverlight Applications property page allows you to add or reference a Silverlight project that can be embedded into the web site. This is discussed in more detail in Chapter 22.

Creating a Web Application Project

Creating a Web Application project with Visual Studio 2010 is much the same as creating any other project type. Select File

Creating a Web Application Project
Figure 20-4

Figure 20-4. Figure 20-4

The notable difference in available project templates is that the reporting template is not available as a Web Application project. However, the Web Application project type includes templates for creating several different types of server controls.

Once you click OK your new Web Application project will be created with a few more items than the Web Site projects. It includes an AssemblyInfo file, a References folder, and a My Project item under the Visual Basic or Properties node under C#.

You can view the project properties pages for a Web Application project by double-clicking the Properties or My Project item. The property pages include an additional Web page, as shown in Figure 20-5.

Figure 20-5

Figure 20-5. Figure 20-5

The options on the Web page are all related to debugging an ASP.NET web application and are covered in Chapter 42, "Debugging Web Applications," and Chapter 43, "Advanced Debugging Techniques."

Other Web Projects

In addition to the standard ASP.NET Web Site and Web Application project templates are templates that provide solutions for more specific scenarios:

  • ASP.NET MVC 2 Web Application: This creates a web application using the Model-View-Controller (MVC) architecture. This is only available as a Web Application project and is discussed in Chapter 21.

  • ASP.NET Web Service: This creates a default Web service called Sevice.asmx, which contains a sample Web method. This is only available as a Web Application project when the target is .NET Framework 3.5 or earlier.

  • ASP.NET Reports Web Site: This creates an ASP.NET web site with a report (.rdlc) and a ReportViewer control bound to the report. This is only available as a Web Site project and is explained in Chapter 30.

  • ASP.NET Crystal Reports Web Site: This creates an ASP.NET web site with a sample Crystal Report. This is only available as a Web Site project.

  • ASP.NET Server Control: Server controls include standard elements such as buttons and textboxes, and also special-purpose controls such as a calendar, menus, and tree view control. This template is only available as a Web Application project.

  • ASP.NET AJAX Server Control: This contains the ASP.NET web server controls that enable you to add AJAX functionality to an ASP.NET web page. This is only available as a Web Application project.

  • ASP.NET AJAX Server Control Extender: ASP.NET AJAX extender controls improve the client-side behavior and capabilities of standard ASP.NET web server controls. This is only available as a Web Application project.

  • Dynamic Data Web Site and Web Application: Dynamic Data provides a quick way to build data-bound web applications that use either LINQ to SQL or Entity Framework. These are available for both Web Site and Web Application projects, and are covered in Chapter 23.

From time to time, Microsoft releases additional project templates as a separate download. For example, in Visual Studio 2008 the ASP.NET MVC and Silverlight 2.0 project types were released in this manner.

Starter Kits, Community Projects, and Open-Source Applications

One of the best ways to learn any new development technology is to review a sample application. The Microsoft ASP.NET web site contains a list of starter kits and community projects at http://www.asp.net/community/projects. These web applications are excellent reference implementations for demonstrating best practices and good use of ASP.NET components and design.

Unfortunately, many of the starter kits have not been maintained and are still running on older versions of the .NET Framework. However, they are still very useful because they demonstrate a wide range of advanced ASP.NET technologies and techniques including multiple CSS themes, master-detail pages, and user management.

The Microsoft ASP.NET site also contains a list of popular open-source projects that have been built on ASP.NET. One of the more comprehensive projects is the DinnerNow.net sample application, available at http://www.dinnernow.net/. Although it is categorized as an open-source application, it is really a reference implementation of many of the latest technologies from Microsoft.

The DinnerNow.net application is a fictitious marketplace where customers can order food from local restaurants for delivery to their homes or offices. In addition to the latest ASP.NET components, it demonstrates the use of IIS7, ASP.NET AJAX Extensions, LINQ, Windows Communication Foundation, Windows Workflow Foundation, Windows Presentation Foundation, Windows Powershell, and the .NET Compact Framework.

Another great place to find a large number of excellent open-source examples is CodePlex, Microsoft's open-source project-hosting web site. Located at http://www.codeplex.com/, CodePlex is a veritable wellspring of the good, the bad, and the ugly in Microsoft open-source applications.

DESIGNING WEB FORMS

One of the strongest features in Visual Studio 2010 for web developers is the visual design of web applications. The HTML Designer allows you to change the positioning, padding, and margins in Design view, using visual layout tools. It also provides a split view that enables you to simultaneously work on the design and markup of a web form. Finally, Visual Studio 2010 supports rich CSS editing tools for designing the layout and styling of web content.

The HTML Designer

The HTML Designer in Visual Studio is one of the main reasons it's so easy to develop ASP.NET applications. Because it understands how to render HTML elements as well as server-side ASP.NET controls, you can simply drag and drop components from the Toolbox onto the HTML Designer surface to quickly build up a web user interface. You can also quickly toggle between viewing the HTML markup and the visual design of a web page or user control.

The modifications made to the View menu of the IDE are a great example of what Visual Studio does to contextually provide you with useful features depending on what you're doing. When you're editing a web page in Design view, additional menu commands become available for adjusting how the design surface appears (see Figure 20-6).

Figure 20-6

Figure 20-6. Figure 20-6

The three submenus at the top of the View menu — Ruler and Grid, Visual Aids, and Formatting Marks — provide you with a whole bunch of useful tools to assist with the overall layout of controls and HTML elements on a web page.

For example, when the Show option is toggled on the Visual Aids submenu, it draws gray borders around all container controls and HTML tags such as <table> and <div> so you can easily see where each component resides on the form. It also provides color-coded shading to indicate the margins and padding around HTML elements and server controls. Likewise, on the Formatting Marks submenu you can toggle options to display HTML tag names, line breaks, spaces, and much more. The impact of these options in the HTML Designer can be seen in action in Figure 20-6.

The HTML Designer also supports a split view, shown in Figure 20-7, which shows your HTML markup and visual design at the same time. You activate this view by opening a page in design mode and clicking the Split button on the bottom left of the HTML Designer window.

Figure 20-7

Figure 20-7. Figure 20-7

When you select a control or HTML element on the design surface, the HTML Designer highlights it in the HTML markup. Likewise, if you move the cursor to a new location in the markup, it highlights the corresponding element or control on the design surface.

Figure 20-8

Figure 20-8. Figure 20-8

If you make a change to anything on the design surface, that change is immediately reflected in the HTML markup. However, changes to the markup are not always shown in the HTML Designer right away. Instead, you are presented with an information bar at the top of the Design view stating that it is out of sync with the Source view (see Figure 20-8). You can either click the information bar or press Ctrl+Shift+Y to synchronize the views. Saving your changes to the file also synchronizes it.

Note

If you have a widescreen monitor you can orient the split view vertically to take advantage of your screen resolution. Select Tools

Figure 20-8

Another feature worth pointing out in the HTML Designer is the tag navigator breadcrumb that appears at the bottom of the design window. This feature, which is also in the Silverlight and WPF Designers, displays the hierarchy of the current element or control and all its ancestors. The breadcrumb displays the type of the control or element and the ID or CSS class if it has been defined. If the tag path is too long to fit in the width of the HTML Designer window, the list is truncated and a couple of arrow buttons are displayed so you can scroll through the tag path.

The tag navigator breadcrumb displays the path only from the current element to its top-level parent. It does not list any elements outside that path. If you want to see the hierarchy of all the elements in the current document you should use the Document Outline window, shown in Figure 20-9. Select View

Figure 20-8
Figure 20-9

Figure 20-9. Figure 20-9

Positioning Controls and HTML Elements

One of the trickier parts of building web pages is the positioning of HTML elements. Several attributes can be set that control how an element is positioned, including whether it is using a relative or absolute position, the float setting, the z-index, and the padding and margin widths.

Fortunately, you don't need to learn the exact syntax and names of all of these attributes and manually type them into the markup. As with most things in Visual Studio, the IDE is there to assist with the specifics. Begin by selecting the control or element that you want to position in Design view. Then choose Format

Positioning Controls and HTML Elements

After you click OK, the wrapping and positioning style you have chosen and any values you have entered for location and size are saved to a style attribute on the HTML element.

If an element has relative or absolute positioning, you will be able to reposition it in the Design view. Beware, though, of how you drag elements around the HTML Designer, because you may be doing something you didn't intend! Whenever you select an element or control in Design view, a white tag appears at the top-left corner of the element. This displays the type of element, as well as the ID and class name if they are defined.

Figure 20-10

Figure 20-10. Figure 20-10

If you want to reposition an element with relative or absolute positioning, drag it to the new position using the white control tag. If you drag the element using the control itself, it does not modify the HTML positioning, but instead moves it to a new line of code in the source.

Figure 20-11 shows a button that has relative positioning and has been repositioned. The actual location of the element in the normal flow of the document is shown with an empty blue rectangle. However, this control has been repositioned 45px down and 225px to the right of its original position. The actual control is shown in its new position, and blue horizontal and vertical guidelines are displayed, which indicate that the control is relatively positioned. The guidelines and original position of the element are shown only while it is selected.

Figure 20-11

Figure 20-11. Figure 20-11

Note

If a control uses absolute positioning, the positioning container is highlighted, and two additional guidelines are displayed that extend from the bottom and right of the control to the edge of the container.

The final layout technique discussed here is setting the padding and margins of an HTML element. Many web developers are initially confused about the difference between these display attributes — which is not helped by the fact that different browsers render elements with these attributes differently. Though not all HTML elements display a border, you can generally think of padding as the space inside the border, and of margins as the space outside.

If you look very closely within the HTML Designer, you may notice some gray lines extending a short way horizontally and vertically from all four corners of a control. These are only visible when the element is selected in the Design view. These are called margin handles and they allow you to set the width of the margins. Hover the mouse over the handle until it changes to a resize cursor, and then drag it to increase or decrease the margin width (see Figure 20-12).

Figure 20-12

Figure 20-12. Figure 20-12

Finally, within the HTML Designer you can set the padding around an element. If you select an element and then hold down the Shift key, the margin handles become padding handles. Keeping the Shift key pressed, you can drag the handles to increase or decrease the padding width. When you release the Shift key they revert to margin handles again. Figure 20-12 shows how an HTML image element looks in the HTML Designer when the margin and padding widths have been set on all four sides.

At first, this means of setting the margins and padding can feel counterintuitive, because it does not behave very consistently. To increase the top and left margins you must drag the handlers into the element, and to increase the top and left padding you must drag the handlers away. However, just to confuse things, dragging the bottom and right handlers away from the element increases both margin and padding widths.

Once you have your HTML layout and positioning the way you want them, you can follow good practices by using the new CSS tools to move the layout off the page and into an external style sheet. These tools are discussed in the section after next.

Formatting Controls and HTML Elements

In addition to the Position dialog window discussed in the previous section, Visual Studio 2010 provides a toolbar and a range of additional dialog windows that enable you to edit the formatting of controls and HTML elements on a web page.

The Formatting toolbar, shown in Figure 20-13, provides easy access to most of the formatting options. The leftmost drop-down list lets you control how the formatting options are applied and includes options for inline styling or new CSS rules. The next drop-down list includes all the common HTML elements that can be applied to text, including the <h1> through <h6> headers, <ul>, <ol>, and <blockquote>.

Figure 20-13

Figure 20-13. Figure 20-13

Most of the other formatting dialog windows are listed as entries on the Format menu. These include windows for setting the foreground and background colors, font, alignment, bullets, and numbering. These dialog windows are similar to those available in any word processor or WYSIWYG interface and their uses are immediately obvious.

The Insert Table dialog window, shown in Figure 20-14, provides a way for you to easily define the layout and design of a new HTML table. Open it by positioning the cursor on the design surface where you want the new table to be placed and selecting Table

Figure 20-13

One final and quite useful feature on the Insert Table and Font dialog windows is under the color selector. In addition to the list of Standard Colors, there is also the Document Colors list, shown in Figure 20-15. This lists all the colors that have been applied in some way or another to the current page, for example as foreground, background, or border colors. This saves you from having to remember custom RGB values for the color scheme that you have chosen to apply to a page.

Figure 20-14

Figure 20-14. Figure 20-14

Figure 20-15

Figure 20-15. Figure 20-15

CSS Tools

Once upon a time, the HTML within a typical web page consisted of a mishmash of both content and presentation markup. Web pages made liberal use of HTML tags that defined how the content should be rendered, such as <font>, <center>, and <big>. Nowadays, designs of this nature are frowned upon — best practice dictates that HTML documents should specify only the content of the web page, wrapped in semantic tags such as <h1>, <ul>, and <div>. Elements requiring special presentation rules should be assigned a class attribute, and all style information should be stored in external CSS.

Visual Studio 2010 has several features that provide a rich CSS editing experience in an integrated fashion. As you saw in the previous section, you can do much of the work of designing the layout and styling the content in Design view. This is supplemented by the Manage Styles window, the Apply Styles window, and the CSS Properties window, which are all accessible from the View menu when the HTML Designer is open.

The Manage Styles window lists all the CSS styles that are internal, inline, or in an external CSS file linked through to the current page. The objective of this tool window is to provide you with an overall view of the CSS rules for a particular page, and to enable you to edit and manage those CSS classes.

All the styles are listed in a TreeView with the style sheet forming the top-level nodes, as shown in Figure 20-16. The styles are listed in the order in which they appear in the style sheet file, and you can drag and drop to rearrange the styles, or even move styles from one style sheet to another.

When you hover over a style the tooltip shows the CSS properties in that style, as shown in Figure 20-16. The Options menu drop-down enables you to filter the list of styles to show only those that are applicable to elements on the current page or, if you have an element selected in the HTML Designer, only those that are relevant to the selected element.

Figure 20-16

Figure 20-16. Figure 20-16

Note

The selected style preview, which is at the bottom of the Manage Styles window, is generally not what will actually be displayed in the web browser. This is because the preview does not take into account any CSS inheritance rules that might cause the properties of the style to be overridden.

The Manage Styles window uses a set of icons to provide further visual information about the type of each style. The icons next to the style names have different colors: a red dot indicates an ID-based style, a green dot a class-based style, a blue dot an element-based style, and a yellow dot an inline style.

A circle around a dot indicates that the style is used on the current page. For example, in Figure 20-16 you can quickly see that the title-box CSS class is used on the active web page, whereas the img-box class is not. Finally, the @ symbol is used to indicate an imported external CSS.

When you right-click a style in the Manage Styles window you are given the option to create a new style from scratch, create a new style based on the selected style, or modify the selected style. Any of these three options launch the Modify Style dialog box, shown in Figure 20-17. This dialog provides an intuitive way to define or modify a CSS style. Style properties are grouped into familiar categories, such as Font, Border, and Position, and a useful preview is displayed toward the bottom of the window.

Figure 20-17

Figure 20-17. Figure 20-17

The second of the CSS windows is the Apply Styles window. Though this has a fair degree of overlap with the Manage Styles window, its purpose is to enable you to easily apply styles to elements on the web page. Select View

Figure 20-17

However, the Apply Styles window displays a much more visually accurate representation of the style than the Manage Styles window. It includes the font color and weight, background colors or images, borders, and even text alignment.

When you select an HTML element in the Designer, the styles applied to that element are surrounded by a blue border in the Apply Styles window. This can be seen in Figure 20-18, where the .phone style is active for the selected element. When you hover the mouse over any of the styles a drop-down button appears over it, providing access to a context menu. This menu has options for applying that style to the selected element or, if the style has already been applied, for removing it. Simply clicking the style also applies it to the current HTML element.

Figure 20-18

Figure 20-18. Figure 20-18

The third of the new CSS windows in Visual Studio 2010 is the CSS Properties window, shown in Figure 20-19. This displays a property grid with all the styles used by the HTML element that is currently selected in the HTML Designer. In addition, the window gives you a comprehensive list of all of the available CSS properties. This enables you to add properties to an existing style, modify properties that you have already set, and create new inline styles.

Rather than display the details of an individual style, as was the case with the Apply Styles and Manage Styles windows, the CSS Properties window instead shows a cumulative view of all the styles applicable to the current element, taking into account the order of precedence for the styles. At the top of the CSS Properties window is the Applied Rules section, which lists the CSS styles in the order in which they are applied. Styles that are lower on this list override the styles above them.

Figure 20-19

Figure 20-19. Figure 20-19

Selecting a style in the Applied Rules section shows all the CSS properties for that style in the lower property grid. In Figure 20-19 (left) the .site-nav a CSS rule has been selected, which has a definition for the color, font-size, font-weight, text-decoration, and text-transform CSS properties. You can edit these properties or define new ones directly in this property grid.

The CSS Properties window also has a Summary button, which displays all the CSS properties applicable to the current element. This is shown in Figure 20-19 (right). CSS properties that have been overridden are shown with a red strikethrough, and hovering the mouse over the property displays a tooltip with the reason for the override.

Visual Studio 2010 also includes a Target Rule selector on the Formatting toolbar, shown in Figure 20-20, which enables you to control where style changes you made using the formatting toolbars and dialog windows are saved. These include the Formatting toolbar and the dialog windows under the Format menu, such as Font, Paragraph, Bullets and Numbering, Borders and Shading, and Position.

Figure 20-20

Figure 20-20. Figure 20-20

The Target Rule selector has two modes: Automatic and Manual. In Automatic mode Visual Studio automatically chooses where the new style is applied. In Manual mode you have full control over where the resulting CSS properties are created. Visual Studio 2010 defaults to Manual mode, and any changes to this mode are remembered for the current user.

The Target Rule selector is populated with a list of styles that have already been applied to the currently selected element. Inline styles are displayed with an entry that reads <inline style>. Styles defined inline in the current page have (Current Page) appended, and styles defined in an external style sheet have the filename appended.

Finally, in Visual Studio 2010 there is now IntelliSense support for CSS in both the CSS editor and HTML editor. The CSS editor, which is opened by default when you double-click a CSS file, provides IntelliSense prompts for all the CSS attributes and valid values, as shown in Figure 20-21. After the CSS styles are defined, the HTML editor subsequently detects and displays a list of valid CSS class names available on the web page when you add the class attribute to a HTML element.

Figure 20-21

Figure 20-21. Figure 20-21

Validation Tools

Web browsers are remarkably good at hiding badly formed HTML code from end users. Invalid syntax that would cause a fatal error if it were in an XML document, such as out-of-order or missing closing tags, will often render fine in your favorite web browser. However, if you view that same malformed HTML code in a different browser, it may look totally different. This is one good reason to ensure that your HTML code is standards-compliant.

The first step to validating your standards compliance is to set the target schema for validation. You can do this from the HTML Source Editing toolbar shown in Figure 20-22.

Figure 20-22

Figure 20-22. Figure 20-22

Your HTML markup will be validated against the selected schema. Validation works like a background spell-checker, examining the markup as it is entered and adding wavy green lines under the elements or attributes that are not valid based on the current schema. As shown in Figure 20-23, when you hover over an element marked as invalid a tooltip appears showing the reason for the validation failure. A warning entry is also created in the Error List window.

Figure 20-23

Figure 20-23. Figure 20-23

Schema validation will go a long way toward helping your web pages render the same across different browsers. However, it does not ensure that your site is accessible to everyone. There may be a fairly large group of people with some sort of physical impairment who find it extremely difficult to access your site due to the way the HTML markup has been coded.

The World Health Organization has estimated that about 314 million people worldwide are visually impaired (World Health Organization, 2009). In the United States alone, more than 21 million people have reported experiencing significant vision loss (National Center for Health Statistics, 2006). That's a large body of people by anyone's estimate, especially given that it doesn't include those with other physical impairments.

In addition to reducing the size of your potential user base, if you do not take accessibilities into account you may run the risk of being on the wrong side of a lawsuit. A number of countries have introduced legislation that requires web sites and other forms of communication to be accessible to people with disabilities.

Fortunately, Visual Studio 2010 includes an accessibility-validation tool that checks HTML markups for compliance with accessibility guidelines. The Web Content Accessibility Checker, launched from Tools

Figure 20-23

Select the guidelines to check for compliance and click Validate to begin. Once the web page has been checked, any issues are displayed as errors or warnings in the Error List window, as shown in Figure 20-24.

Figure 20-24

Figure 20-24. Figure 20-24

Note

Previous versions of the ASP.NET web controls rendered markup that generally did not conform to HTML or accessibility standards. Fortunately, for the most part, this has been fixed in ASP.NET version 4.0.

WEB CONTROLS

When ASP.NET version 1.0 was first released, a whole new way of building web applications was enabled for Microsoft developers. Instead of using HTML elements mingled with a server-side scripting language, as was the case with languages such as classic ASP, JSP, and Perl, ASP.NET introduced the concept of feature-rich controls for web pages that acted in ways similar to their Windows counterparts.

Web controls such as button and textbox components have familiar properties such as Text, Left, and Width, along with just as recognizable methods and events such as Click and TextChanged. In addition to these, ASP.NET 1.0 provided a limited set of web-specific components, some dealing with data-based information, such as the DataGrid control, and others providing common web tasks, such as an ErrorProvider to give feedback to users about problems with information they entered into a web form.

Subsequent versions of ASP.NET introduced well over 50 web server controls including navigation components, user authentication, web parts, and improved data controls. Third-party vendors have also released numerous server controls and components that provide even more advanced functionality.

Unfortunately, we don't have room in this book to explore all the server controls available to web applications in much detail. In fact, many of the components, such as TextBox, Button, and Checkbox, are simply the web equivalents of the basic user interface controls that you may well be very familiar with already. However, it will be useful to provide an overview of some of the more specialized and functional server controls that reside in the ASP.NET web developers' toolkit.

Navigation Components

ASP.NET includes a simple way to add site-wide navigation to your web applications with the sitemap provider and associated controls. In order to implement sitemap functionality into your projects, you must manually create the site data, by default in a file called Web.sitemap, and keep it up to date as you add or remove web pages from the site. Sitemap files can be used as a data source for a number of web controls, including SiteMapPath, which automatically keeps track of where you are in the site hierarchy, as well as the Menu and TreeView controls, which can present a custom subset of the sitemap information.

Once you have your site hierarchy defined in a Web.sitemap file, the easiest way to use it is to drag and drop a SiteMapPath control onto your web page design surface (see Figure 20-25). This control automatically binds to the default sitemap provider, as specified in the Web.config file, to generate the nodes for display.

Figure 20-25

Figure 20-25. Figure 20-25

Though the SiteMapPath control displays only the breadcrumb trail leading directly to the currently viewed page, at times you will want to display a list of pages in your site. The ASP.NET Menu control can be used to do this, and has modes for both horizontal and vertical viewing of the information. Likewise, the TreeView control can be bound to a sitemap and used to render a hierarchical menu of pages in a web site. Figure 20-26 shows a web page with a SiteMapPath, Menu, and TreeView that have each been formatted with one of the built-in styles.

Figure 20-26

Figure 20-26. Figure 20-26

User Authentication

Perhaps the most significant additions to the web components in ASP.NET version 2.0 were the new user authentication and login components. Using these components, you can quickly and easily create the user-based parts of your web application without having to worry about how to format them or what controls are necessary.

Every web application has a default data source added to its ASP.NET configuration when it is first created. The data source is a SQL Server Express database with a default name pointing to a local file system location. This data source is used as the default location for your user authentication processing, storing information about users and their current settings.

The benefit of having this automated data store generated for each web site is that Visual Studio can have an array of user-bound web components that can automatically save user information without your needing to write any code.

Before you can sign in as a user on a particular site, you first need to create a user account. Initially, you can do that in the administration and configuration of ASP.NET, which is discussed later in this chapter, but you may also want to allow visitors to the site to create their own user accounts. The CreateUserWizard component does just that. It consists of two wizard pages with information about creating an account, and indicates when account creation is successful.

Once users have created their accounts they need to be able to log in to the site, and the Login control fills this need. Adding the Login component to your page creates a small form containing User Name and Password fields, along with the option to remember the login credentials, and a Log In button (see Figure 20-27).

Figure 20-27

Figure 20-27. Figure 20-27

The trick to getting this to work straightaway is to edit your Web.config file and change the authentication to Forms. The default authentication type is Windows, and without the change the web site authenticates you as a Windows user because that's how you are currently logged in. Obviously, some web applications require Windows authentication, but for a simple web site that you plan to deploy on the Internet, this is the only change you need to make in order for the Login control to work properly.

You can also use several controls that will detect whether the user has logged on, and display different information to an authenticated user as opposed to an anonymous user. The LoginStatus control is a simple bi-state component that displays one set of content when the site detects that a user is currently logged in, and a different set of content when there is no logged-in user. The LoginName component is also simple; it just returns the name of the logged-in user.

There are also controls that allow end users to manage their own passwords. The ChangePassword component works in conjunction with the other automatic user-based components to enable users to change their passwords. However, sometimes users forget their passwords, which is where the PasswordRecovery control comes into play. This component, shown in Figure 20-28, has three views: UserName, Question, and Success. The idea is that users first enter their username so the application can determine and display the security question, and then wait for an answer. If the answer is correct, the component moves to the Success page and sends an e-mail to the registered e-mail address.

Figure 20-28

Figure 20-28. Figure 20-28

The last component in the Login group on the Toolbox is the LoginView object. LoginView enables you to create whole sections on your web page that are visible only under certain conditions related to who is (or isn't) logged in. By default, you have two views: the AnonymousTemplate, which is used when no user is logged in, and the LoggedInTemplate, used when any user is logged in. Both templates have an editable area that is initially completely empty.

However, because you can define specialized roles and assign users to these roles, you can also create templates for each role you have defined in your site (see Figure 20-29). The Edit RoleGroups command on the smart-tag Tasks list associated with LoginView displays the typical collection editor and enables you to build role groups that can contain one or multiple roles. When the site detects that the user logs in with a certain role, the display area of the LoginView component is populated with that particular template's content.

Figure 20-29

Figure 20-29. Figure 20-29

Note

See the "ASP.NET Web Site Administration" section later in this chapter for information on how to create and manage roles.

What's amazing about all of these controls is that with only a couple of manual property changes and a few extra entries in the Web.config file, you can build a complete user-authentication system into your web application. In fact, as you'll see in the "ASP.NET Web Site Administration" section later in this chapter, you can edit all these settings without needing to edit the Web.config file directly. Now that's efficient coding!

Data Components

Data components were introduced to Microsoft web developers with the first version of Visual Studio .NET and have evolved to be even more powerful with each subsequent release of Visual Studio. Each data control has a smart-tag Tasks list associated with it that enables you to edit the individual templates for each part of the displayable area. For example, the DataList has seven templates in all, which can be individually customized (see Figure 20-30).

Figure 20-30

Figure 20-30. Figure 20-30

Data Source Controls

The data source control architecture in ASP.NET provides a really simple way for UI controls to bind to data. The data source controls that were released with ASP.NET 2.0 include SqlDataSource and AccessDataSource for binding to SQL Server or Access databases, ObjectDataSource for binding to a generic class, XmlDataSource for binding to XML files, and SiteMapDataSource for the site navigation tree for the web application.

ASP.NET 3.5 shipped with a LinqDataSource control that enables you to directly bind UI controls to data sources using Language Integrated Query (LINQ). The EntityDataSource control, released with ASP.NET 3.5 SP1, supports data binding using the ADO.NET Entity Framework. These controls provide you with a designer-driven approach that automatically generates most of the code necessary for interacting with the data.

All data source controls operate in a similar way. For the purposes of this discussion, the remainder of this section uses the LinqDataSource as an example.

Before you can use LinqDataSource, you must already have a DataContext class created. The data context wraps a database connection in order to provide object lifecycle services. Chapter 28 explains how to create a new DataContext class in your application.

You can then create a LinqDataSource control instance by dragging it from the Toolbox onto the design surface. To configure the control, launch the Configure Data Source Wizard under the smart tag for the control. Select the data context class, and then choose the data selection details you want to use. Figure 20-31 shows the screen within the Configure Data Source Wizard that enables you to choose the tables and columns to generate a LINQ to SQL query. It is then a simple matter to bind this data source to a UI server control, such as the ListView control, in order to provide read-only access to your data.

Figure 20-31

Figure 20-31. Figure 20-31

You can easily take advantage of more advanced data access functionality supported by LINQ, such as allowing inserts, updates, and deletes, by setting the EnableInsert, EnableUpdate, and EnableDelete properties on LinqDataSource to true. You can do this either programmatically in code or through the property grid.

You can find more information on LINQ in Chapter 28.

Data View Controls

Once you have specified a data source it is a simple matter to use one of the data view controls to display this data. ASP.NET ships with eight built-in web controls that render data in different ways including Chart, DataList, DetailsView, FormView, GridView, ListView, and Repeater. The Chart control is used to render data graphically using visualizations such as a bar chart or line chart and is discussed in Chapter 30.

A common complaint about the ASP.NET server controls is that developers have very little control over the HTML markup they generate. This is especially true of many of the data view controls such as GridView, which always uses an HTML table to format the data it outputs, even though in some situations an ordered list would be more suitable.

The ListView control provides a good solution to the shortcomings of other data controls in this area. Instead of surrounding the rendered markup with superfluous <table> or <span> elements, it enables you to specify the exact HTML output that is rendered. The HTML markup is defined in the 11 templates that ListView supports:

  • AlternatingItemTemplate

  • EditItemTemplate

  • EmptyDataTemplate

  • EmptyItemTemplate

  • GroupSeparatorTemplate

  • GroupTemplate

  • InsertItemTemplate

  • ItemSeparatorTemplate

  • ItemTemplate

  • LayoutTemplate

  • SelectedItemTemplate

The two most useful templates are LayoutTemplate and ItemTemplate. LayoutTemplate specifies the HTML markup that surrounds the output, and ItemTemplate specifies the HTML used to format each record that is bound to the ListView.

When you add a ListView control to the design surface, you can bind it to a data source and then open the Configure ListView dialog box shown in Figure 20-32, via smart-tag actions. This provides a code-generation tool that automatically produces HTML code based on a small number of predefined layouts and styles.

Figure 20-32

Figure 20-32. Figure 20-32

Note

Because you have total control over the HTML markup, the Configure ListView dialog box does not even attempt to parse any existing markup. Instead, if you reopen the window it simply shows the default layout settings.

Data Helper Controls

The DataPager control is used to split the data that is displayed by a UI control into multiple pages, which is necessary when you're working with very large data sets. It natively supports paging via either a NumericPagerField object, which lets users select a page number, or a NextPreviousPagerField object, which lets users navigate to the next or previous page. As with the ListView control, you can also write your own custom HTML markup for paging by using the TemplatePagerField object.

Finally, the QueryExtender control, new to ASP.NET version 4.0, provides a way to filter data from an EntityDataSource or LinqDataSource in a declarative manner. It is particularly useful for searching scenarios.

Web Parts

Another excellent feature in ASP.NET is the ability to create Web Parts controls and pages. These allow certain pages on your site to be divided into chunks that either you or your users can move around, and show and hide, to create a unique viewing experience. Web Parts for ASP.NET are loosely based on custom web controls but owe their inclusion in ASP.NET to the huge popularity of Web Parts in SharePoint Portals.

With a Web Parts page, you first create a WebPartManager component that sits on the page to look after any areas of the page design that are defined as parts. You then use WebPartZone containers to set where you want customizable content on the page, and then finally place the actual content into the WebPartZone container.

Though these two components are the core of Web Parts, you need only look at the WebParts group in the Toolbox to discover a whole array of additional components (see Figure 20-33). You use these additional components to enable your users to customize their experience of your web site.

Unfortunately, there is not enough space in this book to cover the ASP.NET web controls in any further detail. If you want to learn more, we recommend you check out the massive Professional ASP.NET 4 in C# and VB by Bill Evjen, Scott Hanselman, and Devin Rader.

Figure 20-33

Figure 20-33. Figure 20-33

MASTER PAGES

A very useful feature of web development in Visual Studio is the ability to create master pages that define sections that can be customized. This enables you to define a single page design that contains the common elements that should be shared across your entire site, specify areas that can house individualized content, and inherit it for each of the pages on the site.

To add a master page to your Web Application project, use the Add New Item command from the web site menu or from the context menu in the Solution Explorer. This displays the Add New Item dialog, shown in Figure 20-34, which contains a large number of item templates that can be added to a web application. You'll notice that besides Web Forms (.aspx) pages and Web User Controls, you can also add plain HTML files, style sheets, and other web-related file types. To add a master page, select the Master Page template, choose a name for the file, and click Add.

Figure 20-34

Figure 20-34. Figure 20-34

When a master page is added to your web site, it starts out as a minimal web page template with two empty ContentPlaceHolder components — one in the body of the web page and one in the head. This is where the detail information can be placed for each individual page. You can create the master page as you would any other web form page, complete with ASP.NET and HTML elements, CSSs, and theming.

If your design requires additional areas for detail information, you can either drag a new ContentPlaceHolder control from the Toolbox onto the page, or switch to Source view and add the following tags where you need the additional area:

<asp:ContentPlaceHolder id="aUniqueid" runat="server">
</asp:ContentPlaceHolder>

Once the design of your master page has been finalized, you can use it for the detail pages for new web forms in your project.

Unfortunately, the process to add a form that uses a master page is slightly different depending on whether you are using a Web Application or Web Site project. For a Web Application project, rather than adding a new Web Form you should add a new Web Form using Master Page. This displays the Select a Master Page dialog box shown in Figure 20-35. In a Web Site project, the Add New Item window contains a checkbox titled Select Master Page. If you check this, the Select a Master Page dialog is displayed.

Figure 20-35

Figure 20-35. Figure 20-35

Select the master page to be applied to the detail page and click OK. The new web form page that is added to the project will include one or more Content controls, which map to the ContentPlaceHolder controls on the master page.

It doesn't take long to see the benefits of master pages and understand why they have become a very popular feature. However, it is even more useful to create nested master pages.

Working with nested master pages is not much different from working with normal master pages. To add one, select Nested Master Page from the Add New Item window. You are prompted to select the parent master page via the Select a Master Page window that was shown in Figure 20-35. When you subsequently add a new content web page, any nested master pages are also shown in the Select a Master Page window.

RICH CLIENT-SIDE DEVELOPMENT

In the past couple of years the software industry has seen a fundamental shift toward emphasizing the importance of the end user experience in application development. Nowhere has that been more apparent than in the development of web applications. Fueled by technologies such as AJAX and an increased appreciation of JavaScript, we are now expected to provide web applications that approach the richness of their desktop equivalents.

Microsoft has certainly recognized this and includes a range of tools and functionality in Visual Studio 2010 that support the creation of rich client-side interactions. There is integrated debugging and IntelliSense support for JavaScript. ASP.NET AJAX is shipped with Visual Studio 2010, and there is support in the IDE for AJAX Control Extenders. These tools make it much easier for you to design, build, and debug client-side code that provides a much richer user experience.

Developing with JavaScript

Writing JavaScript client code has long had a reputation for being difficult, even though the language itself is quite simple. Because JavaScript is a dynamic, loosely typed programming language — very different from the strong typing enforced by Visual Basic and C# — JavaScript's reputation is even worse in some .NET developer circles.

Thus, one of the most useful features of Visual Studio for web developers is IntelliSense support for JavaScript. You will notice the IntelliSense beginning immediately as you start typing, with prompts for native JavaScript functions and keywords such as var, alert, and eval.

Furthermore, the JavaScript IntelliSense in Visual Studio 2010 automatically evaluates and infers variable types to provide more accurate IntelliSense prompts. For example, in Figure 20-36 you can see that IntelliSense has determined that optSelected is an HTML object, because a call to the document.getElementByID function will return that type.

Figure 20-36

Figure 20-36. Figure 20-36

In addition to displaying IntelliSense within web forms, Visual Studio also supports IntelliSense in external JavaScript files. It also provides IntelliSense help for referenced script files and libraries, such as the Microsoft AJAX library.

Microsoft has extended the XML commenting system in Visual Studio to recognize comments on JavaScript functions. IntelliSense detects these XML code comments and displays the summary, parameters, and return type information for the function.

A couple of limitations could prevent the JavaScript IntelliSense from displaying information in certain circumstances, including:

  • A syntax or other error in an external referenced script file.

  • Invoking a browser-specific function or object. Most web browsers provide a set of objects that is proprietary to that browser. You can still use these objects, and in fact many popular JavaScript frameworks do; however, you won't get IntelliSense support for them.

  • Referencing files that are outside the current project.

Visual Studio constantly monitors changes to files in the project and updates the IntelliSense as they happen. If for some reason you find that Visual Studio isn't displaying the latest information, you can force it to update the IntelliSense by selecting Edit

Figure 20-36

One new feature in the latest version of ASP.NET is the ClientIDMode property that has been added to web server controls. In previous versions, the value that was generated for the id attribute on generated HTML controls made it difficult to reference these controls in JavaScript. The ClientIDMode property fixes this by defining two new modes (Static and Predictable) for generating these ids in a simpler and more predictable way.

The updated JavaScript IntelliSense support, combined with the improved client-side debugging and better control over client IDs, significantly reduces the difficulty of developing JavaScript code with Visual Studio 2010.

Working with ASP.NET AJAX

The ASP.NET AJAX framework provides web developers with a familiar server-control programming approach for building rich client-side AJAX interactions.

ASP.NET AJAX includes both server-side and client-side components. A set of server controls, including the popular UpdatePanel and UpdateProgess controls, can be added to web forms to enable asynchronous partial-page updates without your needing to make changes to any existing code on the page. The client-side Microsoft AJAX Library is a JavaScript framework that can be used in any web application, such as PHP on Apache, and not just ASP.NET or IIS.

The following walkthrough demonstrates how to enhance an existing web page by adding the ASP.NET AJAX UpdatePanel control to perform a partial-page update. In this scenario we have a very simple web form with a DropDownList server control, which has an AutoPostBack to the server enabled. The web form handles the DropDownList.SelectedIndexChanged event and saves the value that was selected in the DropDownList to a TextBox server control on the page. The code listing for this page is as follows:

AjaxSampleForm.aspx
<%@ Page Language="vb" AutoEventWireup="false"
   CodeBehind="AjaxSampleForm.aspx.vb"
   Inherits="ASPNetWebApp.AjaxSampleForm" %>
<!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>ASP.NET AJAX Sample</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        Select an option:
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
            <asp:ListItem Text="Option 1" Value="Option 1" />
            <asp:ListItem Text="Option 2" Value="Option 2" />
            <asp:ListItem Text="Option 3" Value="Option 3" />
</asp:DropDownList>
        <br />
        Option selected:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>
AjaxSampleForm.aspx.vb
Public Partial Class AjaxSampleForm
    Inherits System.Web.UI.Page
    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, _
                                                     ByVal e As EventArgs) _
                                         Handles DropDownList1.SelectedIndexChanged
        System.Threading.Thread.Sleep(2000)
        Me.TextBox1.Text = Me.DropDownList1.SelectedValue
    End Sub
End Class

Notice that in the DropDownList1_SelectedIndexChanged method we have added a statement to sleep for two seconds. This will exaggerate the server processing time, thereby making it easier to see the effect of the changes we will make. When you run this page and change an option in the drop-down list, the whole page will be refreshed in the browser.

The first AJAX control that you need to add to your web page is a ScriptManager. This is a nonvisual control that's central to ASP.NET AJAX and is responsible for tasks such as sending script libraries and files to the client and generating any required client proxy classes. You can have only one ScriptManager control per ASP.NET web page, which can pose a problem when you're using master pages and user controls. In that case, you should add the ScriptManager to the topmost parent page, and a ScriptManagerProxy control to all child pages.

After you add the ScriptManager control, you can add any other ASP.NET AJAX controls. In this case, add an UpdatePanel control to the web page, as shown in the following listing. Notice that TextBox1 is now contained within the new UpdatePanel control.

<%@ Page Language="vb" AutoEventWireup="false"
   CodeBehind="AjaxSampleForm.aspx.vb"
   Inherits="ASPNetWebApp.AjaxSampleForm" %>
<!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>ASP.NET AJAX Sample</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <div>
        Select an option:
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
            <asp:ListItem Text="Option 1" Value="Option 1" />
            <asp:ListItem Text="Option 2" Value="Option 2" />
<asp:ListItem Text="Option 3" Value="Option 3" />
        </asp:DropDownList>
        <br />
        Option selected:
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="DropDownList1"
                                          EventName="SelectedIndexChanged" />
            </Triggers>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

The web page now uses AJAX to provide a partial-page update. When you now run this page and change an option in the drop-down list, the whole page is no longer refreshed. Instead, just the text within the textbox is updated. In fact, if you run this page you will notice that AJAX is too good at just updating part of the page. There is no feedback and if you didn't know any better you would think that nothing is happening. This is where the UpdateProgress control becomes useful. You can place an UpdateProgress control on the page, and when an AJAX request is invoked the HTML within the ProgressTemplate section of the control is rendered. The following listing shows an example of an UpdateProgress control for our web form:

<asp:UpdateProgress ID="UpdateProgress1" runat="server">
    <ProgressTemplate>
        Loading.
    </ProgressTemplate>
</asp:UpdateProgress>

The final server control in ASP.NET AJAX that hasn't been mentioned is the Timer control, which enables you to perform asynchronous or synchronous client-side postbacks at a defined interval. This can be useful for scenarios such as checking with the server to see if a value has changed.

Once you have added some basic AJAX functionality to your web application, you can further improve the client user experience by adding one or more elements from the AJAX Control Toolkit, which is discussed in the following section.

Using AJAX Control Extenders

AJAX Control Extenders provide a way to add AJAX functionality to a standard ASP.NET server control. The best-known set of control extenders is the AJAX Control Toolkit, a free open-source library of client behaviors that includes almost 40 control extenders. These either provide enhancements to existing ASP.NET web controls or provide completely new rich-client UI elements. Figure 20-37 shows a Calendar Extender that has been attached to a TextBox control.

Figure 20-37

Figure 20-37. Figure 20-37

The ASP.NET AJAX Control Toolkit is available for download via a link from http://ajaxcontroltoolkit.codeplex.com. The binary version of the download includes an assembly called AjaxControlToolkit.dll. Copy this to a directory where you won't accidentally delete it.

To add the controls to the Visual Studio Control Toolbox, you should first create a new tab to house them. Right-click anywhere in the Toolbox window, choose Add Tab, and then rename the new tab something meaningful, such as AJAX Control Toolkit. Next, right-click in the new tab and select Choose Items. Click the Browse button and locate the AjaxControlToolkit.dll to add the AJAX controls to the list of available .NET Framework Components. Click OK and the tab will be populated with all the controls in the AJAX Control Toolkit.

Visual Studio 2010 provides designer support for any AJAX Control Extenders, including the AJAX Control Toolkit. Once you have added the controls to the Toolbox, Visual Studio adds an entry to the smart-tag Tasks list of any web controls with extenders, as shown in Figure 20-38.

Figure 20-38

Figure 20-38. Figure 20-38

When you select the Add Extender task it launches the Extender Wizard, shown in Figure 20-39. Choose an extender from the list and click OK to add it to your web form. In most cases, the Extender Wizard will also automatically add a reference to the AJAX Control Toolkit library. However, if it does not you can manually add a binary reference to the AjaxControlToolkit.dll assembly.

Note

Because the Extender Controls are built on top of ASP.NET AJAX, you will need to ensure that a ScriptManager control is on your web form.

Figure 20-39

Figure 20-39. Figure 20-39

As shown in Figure 20-40, Visual Studio 2010 includes all the properties for the control extender in the property grid, under the control to which the extender is attached.

Because the AJAX Control Toolkit is open source, you can customize or further enhance any of the control extenders it includes. Visual Studio 2010 also ships with C# and Visual Basic project templates to create your own AJAX Control Extenders and ASP.NET AJAX Controls. This makes it easy to build rich web applications with UI functionality that can be easily reused across your web pages and projects.

Figure 20-40

Figure 20-40. Figure 20-40

ASP.NET WEB SITE ADMINISTRATION

Although running your web application with default behavior will work in most situations, sometimes you'll need to manage the application settings beyond simply setting the properties of components and page items. The Web Site Administration Tool provides you with a web-based configuration application that enables you to define various security-related settings, such as users and roles, as well as application-wide settings that can come in handy, such as a default error page, and global SMTP e-mail settings that are used by various components, such as the PasswordRecovery control.

To start the Administration Tool, use the Project

ASP.NET WEB SITE ADMINISTRATION

You can determine whether the web server is active by looking in the notification area of your taskbar and finding the development server icon connected to the port that Visual Studio 2010 allocated when it was started up. You can stop an active web server by right-clicking its icon in the notification area and selecting Show Details. When the server information is displayed (see Figure 20-41), click the Stop button to stop the specific instance of the development web server.

Figure 20-41

Figure 20-41. Figure 20-41

Note

Note that stopping an active web server won't affect any other development servers that are currently running.

When the Administration Tool is displayed in your web browser, it shows the application name, accompanied by the name of the current Windows-based authenticated user. The tool has three main sections: security for the creation and maintenance of users, roles, and authentication; application configuration to control application-specific key-value pairs, SMTP settings, and debug configurations; and provider configuration to control the way the user administration data is stored for the site.

Security

The security section of the tool provides you with a summary of the users and roles defined in the site, and the authentication mode. You can change individual settings from this summary page by clicking their associated links, or use the Security Setup Wizard to step through each section of the security settings in turn.

The authentication mode is controlled by the access method page (shown in the wizard in Figure 20-42). If you choose From the Internet, the tool sets the authentication mode to Forms, whereas the From a Local Area Network option results in an authentication mode of Windows.

The most useful part of this tool is the ability it gives you to add and edit roles. In the wizard you'll first need to enable role management by checking the Enable Roles for this Web Site option. Once roles are active you can define them either through the wizard or from the summary page. Each role is defined by a single string value, and it's up to you to control how that role will be used in your web application (with the exception of access rules, which are discussed in a moment).

The next step in the wizard is to create user accounts. The information on this page is a replication of the CreateUserAccount component, and enables you to create an initial user who can serve as administrator for your web site.

Figure 20-42

Figure 20-42. Figure 20-42

The access rules page (shown in Figure 20-43) enables you to restrict access to certain parts of your site to a specific role or user, or to grant access only when any user is logged in. As Figure 20-43 shows, by default there is a single rule (which is actually implicitly defined and inherited from the server) that defines full access to the entire site for all users.

Web site processing will look at the rules in the order in which they are defined, stopping at the first rule that applies to the particular context. For example, if you define first a rule that allows access to the Admin folder for anyone belonging to the Administrator's role, and then define a subsequent rule that denies access to the same folder for all users, it will effectively block access to the Admin folder for all users who do not belong to the Administrator's role.

Once you have users, roles, and rules defined in your site, you can then start applying the access by clicking the Manage Users link from the summary security page. This presents you with a list of all users defined in the system. Click the Edit User or Edit Roles link to specify the roles to which each user belongs.

This information can be used to customize the content in your web pages with the LoginView component discussed earlier in this chapter.

Figure 20-43

Figure 20-43. Figure 20-43

Application Settings

The application section of the Web Site Administration Tool enables you to define and edit application-specific settings in the form of key-value pairs, as well as to configure SMTP e-mail settings, including the default SMTP mail server and sender's e-mail address.

You can also specify what level of debugging you want to perform on the application, and customize the tracing information being kept as you run the application.

ASP.NET Configuration in IIS

If you have already deployed an ASP.NET application to a production server, you can edit the configuration settings directly within Internet Information Services (IIS), located in the Administrative Tools section of the Control Panel. When ASP.NET is installed on a machine, you'll find that each web site (including virtual directories) will have a set of configuration tools in IIS under the property pages, as shown in Figure 20-44.

The tools included in IIS enable you to manage all the settings you saw earlier, including the creation and management of users, roles, application settings, and SMTP settings. You are also given access to more powerful administration tools that enable you to configure advanced settings such as the .NET compilation behavior, .NET trust level, and session state configuration. These tools enable you to maintain a web application running on any IIS server without needing to resort to editing the Web.config configuration file.

Figure 20-44

Figure 20-44. Figure 20-44

SUMMARY

In this chapter you learned how to create ASP.NET applications using the Web Site and Web Application projects. The improvements to the HTML Designer and the new CSS tools in Visual Studio 2010 provide you with great power over the layout and visual design of web pages. The vast number of web controls included in ASP.NET enables you to quickly put together highly functional web pages. Through the judicious use of JavaScript, ASP.NET AJAX, and control extenders in the AJAX Control Toolkit, you can provide a very rich user experience in your web applications.

Of course, there's much more to web development than we covered here. Chapters 21 and 22 continue the discussion on building rich web applications by exploring the latest web technologies from Microsoft: ASP.NET MVC and Silverlight. Chapter 42 provides detailed information about the tools and techniques available for effective debugging of web applications. Finally, Chapter 49 walks you through the deployment options for web applications. If you are looking for more information after this, you should check out Professional ASP.NET 4 in C# and VB by Bill Evjen, Scott Hanselman, and Devin Rader. Weighing in at over 1,600 pages, this is the best and most comprehensive resource available to web developers who are building applications on the latest version of ASP.NET.

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

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