BUY THIS BOOK
Add to Cart

Print Book $29.95


Add to Cart

Print+PDF $38.94

Add to Cart

PDF $23.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £20.95

What is this?

Looking to Reprint or License this content?


ASP.NET 2.0: A Developer's Notebook
ASP.NET 2.0: A Developer's Notebook By Wei-Meng Lee
June 2005
Pages: 348

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: What's New?
Within a few short years, ASP.NET has become one of the favorite tools of web applications developers, and now it's about to undergo its second major upgrade. Microsoft is making major improvements to the product based on feedback from its millions of customers and the company's own experience in developing and deploying web applications. Moreover, the market for web development tools has become increasingly competitive with the rise of open source PHP and Macromedia Flash, both of which have steadily gained market share.
Controls
ASP.NET 2.0 ships with several new controls to make the life of a web application developer easier. In ASP.NET 2.0, there are now new controls that help you to perform data access, site navigation, login, and personalization using Web Parts.
Page Framework
ASP.NET 2.0 supports some useful additions to its Page framework such as visual inheritance, technically known as Master Pages. Besides Master Pages, ASP.NET 2.0 also supports "theming" through Themes and Skins, allowing you to maintain a consistent look-and-feel for your web sites. Another noteworthy feature in ASP.NET is the improved support for localization, which reduces the amount of work you need to do to internationalize your web applications.
Services and APIs
Behind the various new controls in ASP.NET 2.0 lie the foundation services and APIs that do the heavy lifting needed to support the controls. For example, behind the new Login controls you'll find the new collection of Membership APIs, which perform such tasks such as user authentication, registration of new users, etc. Besides using the new controls, you can directly make use of these APIs in code.
Table 1-1 summarizes some of most important new features of ASP.NET 2.0.
Table 1-1:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create a New Web Project
The way you create a new web application project has changed in Visual Studio 2005. In Visual Studio .NET 2003, you select File New Project on the Visual Studio menu and then select the kind of project you want to create (Web, Windows, Windows Services, and so on) in the New Project Dialog. In Visual Studio 2005, you open a new web project with the New Web Site... command in the File menu.
With Visual Studio 2005, it's now easier than ever to start building an ASP.NET web application. You've got to try it to believe it!
To get a feel for how you create a new web application in Visual Studio 2005, try walking through the following steps. First we'll open the application, pick a location to host it for development, and then add a second web form. Finally, we will see how we can debug the application.
  1. You can change the IDE settings (listed in Sidebar 1-2 via Tools Import and Export Settings.... Since this book is all about web development, we naturally suggest you select Web Development Settings. Launch Visual Studio 2005. If you selected the Web Development Settings option in Visual Studio 2005, go to the File menu and select New Web Site..., as shown at the top of Figure 1-1. If you have chosen any other setting, go to the File menu and choose New Web Site... (see the bottom part of Figure 1-1).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Use Multiple Languages
Unlike ASP.NET 1.x, which requires that you use the same language throughout a web application, ASP.NET 2.0 lets you vary your languages from page to page within a project.
You're no longer restricted to using a single language for your web applications.
While support for multiple languages is a useful feature, developers should use it in moderation (and only if necessary). Going with multiple languages in a single project is likely to increase the effort required in maintaining the project, particularly if the application ends up being maintained by someone who's not familiar with all the languages used.
Figure 1-7 shows a project with three pages, each of which is programmed with a different language: VB.NET (Default.aspx), C# (Default2.aspx), or VJ# (Default3.aspx).
VJ# does not support code-behind pages, so none appear for Page3.aspx in the Solution Explorer window.
Figure 1-7: A project with pages using different languages
To verify that you can really mix languages in an ASP.NET 2.0 web application, in this lab you will create an application that uses two languages: VB.NET and C#.
  1. Using the project created in the last lab, add a new Web Form by right-clicking the project name in Solution Explorer and then selecting Add New Item.... Select Web Form from the list of installed templates.
  2. In the Add New Item dialog, you can choose the language you want to use, as shown in Figure 1-8. ASP.NET 2.0 supports three languages: VB2005, C#, and VJ#. Use the default name of Default2.aspx and choose the C# language. Click Add.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Set the Focus of Controls
In earlier versions of ASP.NET, assigning focus to a control involves writing client-side script (such as JavaScript). In ASP.NET 2.0, this process has been much simplified, and you can now set the focus of a control via its Focus( ) method. Consider the example shown in Figure 1-10. If the user clicks on the Single radio button, you would expect the focus to now be assigned to the Age text box. If the Married option is selected, the Spouse Name text box should get the focus.
Figure 1-10: Setting the focus of controls
Look, no JavaScript! Now you set the focus of controls using the new Focus property.
To try out the new Focus( ) method, work through the following steps to implement the form shown in Figure 1-10.
  1. In Visual Studio 2005, create a new ASP.NET 2.0 web application and name it C:\ASPNET20\chap01-ControlFocus.
  2. Add a radio button list and two text box controls to the default Web Form and give them the names shown in Figure 1-11.
    Figure 1-11: Populating the default form with the various controls
  3. Populate the RadioButtonList with two items: Single and Married. To do so, switch to Source View and add the following bold lines:
    <asp:RadioButtonList ID="rblMaritalStatus" 
         runat="server" AutoPostBack="True">
       <asp:ListItem>Single</asp:ListItem>
                         <asp:ListItem>Married</asp:ListItem>
    </asp:RadioButtonList><br />
  4. To ensure that the Spouse Name text box gets the focus when the user selects the Married radio button, and the Age text box gets the focus when the user selects the Single radio button, you need to set the AutoPostBack property of the RadioButtonList control (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Define Multiple Validation Groups on a Page
In ASP.NET 1.x, all controls in a single page are validated together. For example, suppose you have a Search button and a Get Title button, as shown in Figure 1-15. If you use a RequiredFieldValidator validation control on the ISBN text box, then clicking the Search button will not result in a postback if the ISBN text box is empty. This is because the entire page is invalidated as long as one control fails the validation.
Figure 1-15: Multiple forms on a page
By grouping controls into validation groups, you can now independently validate collections of controls.
In ASP.NET 2.0, group validation allows controls in a page to be grouped logically so that a postback in one group is not dependent on another.
The best way to explore this new feature is to create a form with multiple postback controls, add a validator to one of them, and then assign each control to a separate group. In this lab, you'll implement the form shown in Figure 1-15.
  1. Launch Visual Studio 2005 and create a new web site project. Name the project C:\ASPNET20\chap01-Validation.
  2. Populate the default Web Form with the Panel, TextBox, and Button controls shown in Figure 1-16.
    Figure 1-16: A page with multiple controls
  3. In the top panel (Panel control 1), you'll configure the Search button to post the search string to the server, which in turn will redirect to Google's site. To do so, double-click the Search button (btnSearch) and enter the following code on the code-behind to redirect the search string to Google's site:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Insert Client Script into a Page
There are times when you need to insert client-side JavaScript into your page to implement client-side functionalities. Take the example of an eBanking web application. If the user has not been active for a certain period of time after logging in, the application will prompt the user with a pop-up window asking if the user would like to continue. Employing a pop-up window is more likely to draw the user's attention than simply displaying the message on the web page, and this is best implemented with client-side script.
You can now insert client script into your web page as naturally as writing your server-side code.
In ASP.NET 2.0, you can insert client-side script by using the ClientScript property of the Page class.
To see how you can insert a client script into an ASP.NET 2.0 web application, you will create an application that displays the current time in a JavaScript window when the application is loaded.
  1. In Visual Studio 2005, create a new web site project and name it C:\ASPNET20\chap01-ClientScript.
  2. Double-click the default Web Form to switch to the code-behind.
  3. In the Form_Load event, insert a client script onto the page using the RegisterClientScriptBlock( ) method. The following example inserts a JavaScript code that displays the current time on the server. The time will be displayed in a window, as shown in Figure 1-17.
    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load
        '---inserting client-side script
        Dim script As String = _
            "alert('Time on the server is " & Now & "');"
        Page.ClientScript.RegisterClientScriptBlock( _
            Me.GetType, "MyKey", script, True)
    End Sub
    The RegisterClientScriptBlock( ) method is also available in ASP.NET 1.x and appears under the Page class. However, its namespace has changed in ASP.NET 2.0 and appears under the ClientScriptManager class. You can get an instance of the ClientScriptManager class via
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Post to Another Page
ASP.NET 2.0 now allows you to post values from one page to another easily.
Most ASP.NET developers are familiar with the postback feature of ASP.NET server controls. However, in some cases, posting back to the same page is not the desired action—you might need to post to another. For example, you might need to build an application to perform some surveys. Instead of displaying 50 questions on one page, you would like to break it down to 10 questions per page so that the user need not wade through 50 questions in one go. Moreover, answers to certain questions might trigger a related set of questions in another page. In this case, using a conventional postback mechanism for your web pages is clearly not the solution. You might want to post the values (i.e., the answers to the questions) of one page to another. In this situation, you need to be able to cross-post to another page and, at the same time, be able to retrieve the values from the previous page.
In ASP.NET 1.0 and 1.1, there is no easy way to transfer to another page, and most developers resort to using Server.Transfer. Even so, passing values from one page to another this way is a challenge.
In ASP.NET 2.0, cross-page posting is much easier. Controls now inherently support posting to another page via the PostBackUrl attribute.
To see cross-page posting in action, you will create an application that contains two pages. One page lets you choose items from a CheckBoxList control and then lets you cross-post to another page. You will learn how the values that were cross-posted can be retrieved in the destination page. In addition, you will see the difference between cross-page posting and the old Server.Transfer( ) method.
  1. In Visual Studio 2005, create a new web site project and name it C:\ASPNET20\chap01-CrossPagePosting.
  2. Populate the default Web Form with the controls shown in Figure 1-18. The CheckBoxList1 control contains CheckBox controls that let users choose from a list of values. When the "Post to Default2.aspx" button is clicked, you will post the values to
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Selectively Display Groups of Controls
One task that is common in web applications is data collection. For example, you may need to create a page for user registration. On that page, you may want to collect a fair bit of information, such as username, birth date, and perhaps answers to survey questions (often used to collect subscriber information for controlled circulation magazines). A good practice is to split your questions across multiple pages so that the user need not scroll down a page that contains all the questions. Alternatively, ASP.NET 1.x developers often like to use the Panel controls to contain all the questions and then selectively display the relevant panels (and hide the other panels).
Use the new MultiView and Wizard controls to selectively hide and display controls.
In ASP.NET 2.0, the MultiView control takes the drudgery out of creating multiple pages for this task. It allows controls to be contained within multiple View controls (a new control in ASP.NET 2.0), which you can then programmatically display.
To see how the MultiView control works, you will create an application that contains a MultiView control with three View controls embedded in this control. You can then treat each View control like an ordinary Web Form and populate controls in it. You then connect these View controls together so that users can step through them in a specific order.
  1. Launch Visual Studio 2005 and create a new web site project. Name the project C:\ASPNET20\chap01-MultiView.
  2. Double-click the MultiView control (located in the Toolbox under the Standard tab) to add it to the default Web Form.
  3. Double-click the View control (also located in the Toolbox under the Standard tab) and drag and drop it onto the MultiView control. Drag two more View controls onto the MultiView control.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Upload Files to Your Web Site
ASP.NET 2.0 now includes the FileUpload control, allowing web site users to upload files onto the web server for archival or file-submission purposes. For example, students typically need to upload their files to their school's server when they submit their assignment or project work. You'll find the FileUpload control in the Toolbox under the Standard tab.
Uploading files to your web site is made easy with the new FileUpload control.
The Visual Studio designer represents the FileUpload control by adding an empty text box and a Button control to a Web page. To upload the selected file, you need to explicitly trigger an event, such as clicking a button (see the Submit button in Figure 1-30). In the following example, you will build an application that allows users to upload files to a particular directory on the server. You will also check the size of the file uploaded to ensure that users do not upload files that exceed an imposed limit.
  1. Launch Visual Studio 2005 and create a new web site project. Name the project C:\ASPNET20\chap01-FileUpload.
  2. In the Toolbox, double-click the FileUpload control located under the Standard tab to add the control to the default Web Form, Default.aspx.
  3. Add a Button control to the default form, change its Text to "Submit", and name the button "btnSubmit".
  4. Your form should now look like the one shown in Figure 1-30.
    Figure 1-30: The FileUpload control on a Web Form
    Remember to add a Submit button so that you can invoke the FileUpload control.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create an Image Map
Modern web sites use image maps to allow users to navigate to another part of the site, or to initiate an action by clicking on one or more hotspots of an image. For example, you want to display a world map on a page so that users can click on specific parts of the map to see information about a particular country. ASP.NET 2.0 includes a new ImageMap control that allows you to create image maps easily and painlessly.
The ImageMap control can be found in the Visual Studio Toolbox under the Standard tab.
Use the new ImageMap control to display an image map on your web page.
To see how the ImageMap control works, you will use an ImageMap control to display the image of a Pocket PC. You will define three different hotspots of different shapes on the Pocket PC so that users are able to click on the different parts of the image to see more information.
  1. In Visual Studio 2005, create a new web site project and name it C:\ASPNET20\chap01-ImageMap.
  2. Double-click the ImageMap control in the Toolbox to add a control to the default Web Form.
  3. In Solution Explorer, right-click the project name and add a new folder named Images, where you'll store the image used in this project. Save an image named dellaxim.jpg (see Figure 1-32) into the new folder: C:\ASPNET20\chap01-ImageMap\Images\.
    Figure 1-32: Displaying a Pocket PC using the ImageMap control
  4. To display the image in the ImageMap control, set its ImageURL property to point to the file you just saved (Images/dellaxim.jpg ). The ImageMap control will now display the image of a Pocket PC, as shown in Figure 1-32.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Master Pages and Site Navigation
With Visual Studio 2005, ASP.NET now supports visual page inheritance, which is similar to Windows Forms inheritance, for those who have used that popular framework. With ASP.NET 2.0, you can now create a single Master page that contains the common elements used by the pages of your site. You can then create web pages that inherit from the Master page to enforce a common look and feel across your entire site.
Using Master Pages to provide page headers is preferred over the use of Web User controls; only the Master page needs to be changed and the rest will follow!
In ASP.NET 2.0, a new feature known as Master Pages addresses the limitations of using Web User controls for headers and navigational menu information. In ASP.NET 2.0, you can simply construct a Master page that includes your page header information. You then build each page of your site by first inheriting from the site Master page.
Cool! Now Master Pages make it simple to apply a consistent look and feel throughout my site. No more Web User controls to grapple with!
To really understand how Master Pages work, you will build a web application using Master Pages in the next couple of labs. In this lab, you will create a Master page and populate it with some controls.
  1. In Visual Studio 2005, create a new ASP.NET 2.0 web application and name it C:\ASPNET20\chap02-MasterPages.
  2. Add a folder named Images to the project (right-click the project name in Solution Explorer and select Add Folder Regular Folder). Copy the images shown in Figure 2-1 into the new C:\ASPNET20\chap02-MasterPages\Images\ folder. You'll use these images to build your Master page.
    The images can be downloaded from this book's support site: http://www.oreilly.com/catalog/aspnetadn/.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How do I do that?
To really understand how Master Pages work, you will build a web application using Master Pages in the next couple of labs. In this lab, you will create a Master page and populate it with some controls.
  1. In Visual Studio 2005, create a new ASP.NET 2.0 web application and name it C:\ASPNET20\chap02-MasterPages.
  2. Add a folder named Images to the project (right-click the project name in Solution Explorer and select Add Folder Regular Folder). Copy the images shown in Figure 2-1 into the new C:\ASPNET20\chap02-MasterPages\Images\ folder. You'll use these images to build your Master page.
    The images can be downloaded from this book's support site: http://www.oreilly.com/catalog/aspnetadn/.
    Figure 2-1: The images in the Images folder
  3. Now you'll create the Master page. Right-click the project name in Solution Explorer and then select Add New Item....
  4. In the Add New Item dialog, select the Master Page template and use the default name, MasterPage.master, as shown in Figure 2-2. Click Add to create the page.
    Figure 2-2: Adding a Master page to the project
  5. In Solution Explorer, double-click MasterPage.master and you will see an empty web page that contains a single ContentPlaceHolder control.
    The ContentPlaceHolder control is a placeholder for Content pages (pages that inherit from the Master page) to populate with controls.
  6. Populate the MasterPage.master page with content, images, and links by dragging from the Toolbox and dropping onto its surface two Image controls, one Panel control, and four LinkButton controls, as shown in Figure 2-3. Set the properties of each of the controls as follows:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Use a Master Page as a Content Page Template
Using Master Pages and visual inheritance, you can give all your web site Content pages a common look and feel.
Once you've created a Master page, you can create Content pages for your site that use the Master page as a template.
A Content page is a Web Form that uses a Master page.
In this lab, you will add Content pages to your project and give them a consistent look and feel by using the Master page you created in the previous lab. You will then add controls to a Content page and see how ASP.NET combines the content of the Master page and Content pages at runtime.
  1. First, let's create some pages for your web site. Using the project created in the previous lab, add a new Web Form. Right-click the project name in Solution Explorer and select Add New Item.... On the Add New Item page, select Web Form and use its default name (Default2.aspx). Check the "Select master page" checkbox at the bottom of the dialog (see Figure 2-6).
    Figure 2-6: Creating a Content page by selecting a Master page
  2. You will be asked to choose a Master page to use for your form. Select MasterPage.master (see Figure 2-7).
    Figure 2-7: Selecting a Master page
    A Content page can have only one Master page.
  3. Click OK and Visual Studio displays the new page, Default2.aspx, with the contents of the Master page grayed out (see Figure 2-8), indicating that the content of the Master page cannot be edited in the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Modify a Master Page at Runtime
You can flexibly modify the content of the Master page so that it suits the theme of the page.
When a Web Form that uses a Master page is loaded at runtime, it displays the content of the Master page together with its own content. However, there are times when you will want to modify parts of the Master page when a particular web page is loaded. For example, at the O'Reilly Network site (http://www.oreillynet.com), pages that belong to the ONDotnet subsite display the ONDotnet logo (a leaping dolphin) in their headers, rather than the generic O'Reilly Network logo (the ever-familiar tarsier). Pages at other subsites, such as Perl.com and ONLamp.com, do likewise.
To see how a Master page can be modified on the fly, we'll add a page to our previous project (see Section 2.2). This page will use MasterPage.master and change the image in the Master page from the O'Reilly Network logo to the ONDotnet logo when it is loaded.
  1. Using the project created in the previous lab, add a new Web Form (right-click the project name in Solution Explorer, select Add New Item..., and then select Web Form) and check the "Select master page" checkbox at the bottom of the dialog. Name the Web Form ONDotnet.aspx. Click Add.
  2. Select Masterpage.master as the Master page.
  3. Populate the ONDotnet.aspx Web Form with text (see Figure 2-14).
    Figure 2-14: The ONDotnet.aspx Web Form with text added
  4. Switch to Source View and insert the MasterType directive after the Page directive. The MasterType directive allows you to indicate a strongly typed reference to the Master page so that you can programmatically access its content (such as its public properties and methods):
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create a Site Map for Your Web Site
Your users will never be lost again if you create a site map for your web site!
Unless your web site contains only a single web page, you need a way for users to easily navigate between the pages of your site. In ASP.NET 2.0, there are four new controls that make it easy to implement site navigation. These controls are:
SiteMapDataSource
A control that represents a site map. A site map is an XML file that describes the logical structure of a web site and the relationship between its pages. The SiteMapDataSource control is not visible on the page when it is loaded, but its role is to act as a supplier of site information (taken from the site map file) to the SiteMapPath control.
SiteMapPath
A visual control that depicts the path to the current page, "bread crumb" style.
Menu
A visual control that displays information in menu form. The Menu control supports data binding to a site map.
TreeView
A visual control that displays information in a hierarchical structure. The TreeView control supports data binding to a site map.
In the remaining labs in this chapter, you will learn how to use these controls to make it easy for users to navigate your web site. But first, let's take a closer look at the SiteMapDataSource and SiteMapPath controls.
In this lab, you'll see how you can use the SiteMapPath control together with the Web.sitemap file to display navigation paths on your site pages. First, you'll create a web application that uses a Master page. When a Master page is used as a template for all other pages in a site, it's a good place to put a site map and controls that help users find their way around, because that information will be visible on every page a user visits. You'll create a site map file that describes the logical relationship between the pages of your site, and then you'll add a SiteMapPath control to the Master page so users can see where they are in the hierarchy and move "up" and "down" the path to their current page.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Display Hierarchical Data Using the TreeView Control
At last, a TreeView control that comes right in the box of Visual Studio 2005.
If you have ever visited the MSDN Library site, you will no doubt have noticed the tree-like navigational menu on the left side of its home page (see Figure 2-24).
Figure 2-24: The tree-like navigation on the MSDN site
This information is displayed using the TreeView control, which provides an alternative to the SiteMapPath control for navigating your site. Tree maps are great for displaying hierarchical information and, unlike the SiteMapPath control, they let you browse the entire site, not just the path leading to your current page.
Using the project created in the last lab, let's add a TreeView control to the site. You'll do this by adding the control to your Master page and binding it to your site map so that users can navigate your site by directly clicking the items in the TreeView control.
  1. In the MasterPage.master Master page, add a 2 1 table (Layout Insert Table). Add a TreeView control to the left cell of the table and drag the ContentPlaceHolder control into the right cell (see Figure 2-25).
    Figure 2-25: Populating the Master page
  2. In the TreeView Tasks menu of the TreeView control, select <New data source...> (see Figure 2-27).
    Figure 2-26: Adding the TreeView control to the Master page
  3. In the Data Source Configuration Wizard dialog, select Site Map and then click OK (see Figure 2-27).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Populate a TreeView Control Programmatically
Instead of statically binding the TreeView control to a site map or XML file, gain flexibility by creating it dynamically during runtime.
In other labs in this chapter, you have seen how the TreeView control can be bound to site map files as well as XML documents at design time. However, you can also build your TreeView control dynamically, one node at a time. For example, you might want to display a particular disk directory using the TreeView control, or you may have a site that is changing frequently and hence it is much more efficient to build the tree dynamically.
In this lab, you will use the TreeView control to display the current application path and its subdirectories.
In this lab, you will learn how to customize the TreeView control and dynamically populate it with items. Specifically, you will display the current application path and all its subdirectories in the TreeView control.
  1. Launch Visual Studio 2005 and create a new ASP.NET 2.0 web application. Name the project C:\ASPNET20\chap02-DynamicTreeView.
  2. Drag and drop a TreeView control onto the default Web Form.
  3. In Solution Explorer, right-click the project name and select Add New Folder Regular Folder. Name the folder Images, since you'll use this folder to store your image files.
  4. Add the images shown in Figure 2-36 to the C:\ASPNET20\chap02-DynamicTreeView\Images folder.
    The images can be downloaded from this book's support site at http://www.oreilly.com/catalog/aspnetadn/.
    Figure 2-36: The images in the Images folder
  5. In the TreeView Tasks window, check the Show Lines checkbox and then click the Customize Line Images... link (see Figure 2-37).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Display Drop-Down Menus Using the Menu Control
You can now use the Menu control in ASP.NET 2.0 to menu on the client side. No more client-side script!
Besides using the TreeView control to display site information, you can also use the Menu control to automatically generate a drop-down menu on the browser using client-side script. Sometimes menus are a useful means of navigating a site. For example, Nissan Motors USA (http://www.nissanusa.com) uses menus to allow visitors of their site to choose the various vehicle models they want to view.
In this lab, you will add a Menu control to the Master page created in the earlier lab Section 2.5. The user will then be able to use the Menu control to navigate your site.
  1. Using the project created in the lab Section 2.5, add a Menu control (found in the Standard tab of the Toolbox) to the Master page and apply the "Colorful" theme (via the Auto Format... link in the MenuTasks menu) to change its look (see Figure 2-41).
    Figure 2-41: Customizing the Menu control
  2. In the Menu Tasks of the Menu control, select SiteMapDataSource1 as its data source (see Figure 2-42). The SiteMapDataSource1 control was added when the TreeView control was configured earlier.
    Figure 2-42: Adding a Menu control to the Master page
  3. To test the Menu control, press F5. You should now be able to navigate the site using the Menu control (see Figure 2-43).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Web Parts
Web sites today contain a wealth of information, so much that a poorly designed site can easily overwhelm users. To better help users cope, portal web sites today (such as MSN) often organize their data into discrete units that support a degree of personalization. Information is organized into standalone parts, and users can rearrange those parts to suit their individual working styles. Such personalization also lets users hide parts that contain information in which they have no interest. What's more, users can save their settings so that the site will remember their preferences the next time they visit the site. In ASP.NET 2.0, you can now build web portals that offer this kind of modularization of information and personalization using the new Web Parts Framework.
Add Web Parts to your page so that positions of the controls can be rearranged by the user.
ASP.NET 2.0 provides a set of ready-made controls to help you develop Web Parts for your portals. You'll find the available controls on the WebParts tab of the Toolbox. Let's start with the basics. In this lab, you will learn how to create Web Parts for your ASP.NET web application.
To understand how Web Parts work, let's build a simple portal page that contains three Web Parts.
There are two ways to add a Web Part to a page:
  • By dropping an existing web server control onto the page
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How do I do that?
To understand how Web Parts work, let's build a simple portal page that contains three Web Parts.
There are two ways to add a Web Part to a page:
  • By dropping an existing web server control onto the page
  • By creating a Web User control from scratch and then dropping that onto the page
Either way, you must first prepare the way for these controls by adding a WebPartManagerControl and one or more WebPartZone controls to the page.
WebPartManager
Manages all Web Parts controls on a page.
WebPartZone
Contains and provides overall layout for the Web Part controls that compose the main UI of a page. This control serves as an anchor for Web Part controls.
Let's start by creating a Web Part from a standard web server control.
  1. First you need to create a home page for the Web Parts. Launch Visual Studio 2005 and create a new web site project. Name the project C:\ASPNET20\chap03-Webparts.
  2. Next, drag and drop a WebPartMenuManager control from the Toolbox (under the WebParts tab) onto the default Web Form. The WebPartManager control manages all the Web Parts on a Web Form and must be the first control that you add to the page.
  3. To specify where the Web Parts on your page are to be located, insert a 3 1 table onto the form (Layout Table) and drag and drop a WebPartZone control from the Toolbox (under the WebParts tab) into each of its three cells (see Figure 3-1). Each WebPartZone control will serve as the docking area for one or more Web Parts (more on this in Step 5).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create a Personalizable Custom Web Part
Learn how to create a personalizable custom Web Part and see how it can be exported to a file.
In the previous lab you have seen how to create a Web Part by using either a web server control or a Web User control. In this lab, you will learn another way of creating Web Parts: using a custom control. By using a custom control you gain the flexibility to design your own UI for the Web Part. But more importantly, by inheriting from the WebPart class you also are able to perform tasks that would not ordinarily be available, such as exporting a Web Part to a file. Also, you will learn how you can create personalizable Web Parts that are able to persist information in the Web Part for each specific user.
Personalizable Web Parts are also applicable to a Web User control.
In this lab, you will add a custom Web Control Library to the solution created in the previous lab. The Web Control Library project template allows you to create a custom web control, and in this lab you will learn how to convert this control into a Web Part control. This custom control will consume a translation web service that translates words from English to French. The control will also save the last word (to be translated) so that when the user visits the page again, that word will be displayed.
  1. First, you'll need to create the Web Control Library. Launch Visual Studio 2005 and add a new Web Control Library project (File Add New Project) to the project created in the last lab (C:\ASPNET20\chap03-Webparts). Name the project C:\ASPNET20\chap03-TranslationWebPart (see Figure 3-11).
    Figure 3-11: Adding a new Web Control Library project to the current project
  2. Add a Web Reference (right-click the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Let Users Move Web Parts
Let your users rearrange the positions of the Web Parts on your portal to their liking.
So far we have been discussing how to create Web Parts and how to configure them to look good and nice. But we have not really touched on the most important feature of Web Parts—that is, how to let users move the Web Parts from one zone to another.
In this lab, you will learn how to use the ASP.NET 2.0 Web Parts Framework to enable users to move Web Parts directly in the web browser. First you'll add a pair of radio buttons to the page so you can turn the feature on and off, and then you'll observe the behavior of the Web Parts as you move them from one zone to another.
  1. Using the project created in the previous lab (C:\ASPNET20\chap03-Webparts), add a RadioButtonList control onto the form (see Figure 3-20) and populate it with two items: a radio button named Browse Display Mode and another one named Design Display Mode. Also, check the AutoPostBack checkbox in the RadioButtonList control Tasks menu:
    <asp:RadioButtonList ID="rblMode" runat="server" AutoPostBack="True">
        <asp:ListItem>Browse Display Mode</asp:ListItem>
        <asp:ListItem>Design Display Mode</asp:ListItem>
    </asp:RadioButtonList>
    Figure 3-20: Adding a RadioButtonList control to the form
  2. Double-click the RadioButtonList control to switch to its code-behind page, and then enter the following code. The WebPartManager control manages the display mode of all the Web Parts on the page. By default, all Web Parts under its control are set to browse display mode (BrowseDisplayMode). To allow users to move Web Parts, you need to set the display mode to design display mode (DesignDisplayMode).
    Protected Sub rblMode_SelectedIndexChanged( _
                  ByVal sender As Object, _
                  ByVal e As System.EventArgs) _
                  Handles rblMode.SelectedIndexChanged
        Select Case rblMode.SelectedIndex
            Case 0 : WebPartManager1.DisplayMode = _
                        WebPartManager.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Let Users Add Web Parts at Runtime
Content preview·Buy PDF of this chapter|