Partager via


Walkthrough: Controlling ASP.NET Menus Programmatically

This walkthrough illustrates how to work with the ASP.NET Menu control programmatically by coordinating two menus on the same page using code.

You can create navigational menus for your Web site using the ASP.NET Menu control. In this walkthrough, you explore the programmatic aspects of the ASP.NET Menu control and create two menus bound to the same Web.sitemap file that work together. The first menu is a statically displayed menu of categories such as products, services, and support. It will appear horizontally across the top of the page. The second menu is displayed horizontally below the first menu. The content of the second menu is determined by which menu item is selected in the first. Based on the current selection of the first menu, you programmatically adjust the site map data source of the second menu to show only that portion of the Web.sitemap file that is relevant to the selected category.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Visual Web Developer (Visual Studio).

  • The .NET Framework.

Creating the Web Site

If you have already created a Web site in Visual Web Developer (for example, by following the steps in Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and skip to "Making the Site Map File" later in this walkthrough. Otherwise, create a new Web site and page by following these steps.

This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio.

To create a file system Web site

  1. Open Visual Web Developer.

  2. On the File menu, click NewWeb Site.

    The New Web Site dialog box appears.

  3. Under Visual Studio installed templates, click ASP.NET Web Site.

  4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site.

    For example, type the folder name C:\WebSites.

  5. In the Language list, click the programming language you prefer to work in.

  6. Click OK.

    Visual Web Developer creates the folder and a new page named Default.aspx.

Making the Site Map File

Both menus derive their content from the site's Web.sitemap file. The SiteMapDataSource objects you create are used by both menus to ensure that each displays the appropriate portion of the site map.

To create the Web.sitemap file

  1. In Solution Explorer, right-click the name of your Web site, and then click Add New Item.

  2. In the Add New Item dialog box, choose Site Map and then click Add.

  3. Add the following XML code to the new file. The XML represents a hierarchy of menu choices. The <siteMapNode> elements are nested. Each node is a menu item that contains subitems, and some subitems have subitems of their own. There are three second-level nodes below the Home node: Hardware, Software, and Support. Beneath them are various subcategories.

    <?xml version="1.0" encoding="utf-8" ?>
    <siteMap>
      <siteMapNode title="Home">
        <siteMapNode title="Products">
          <siteMapNode title="Hardware" url="Default.aspx?node=hardware">
            <siteMapNode title="Mouse"/>
            <siteMapNode title="Keyboard"/>
            <siteMapNode title="NetCard"/>
            <siteMapNode title="Monitor"/>
            <siteMapNode title="PC"/>
          </siteMapNode>
          <siteMapNode title="Software" url="Default.aspx?node=software">
            <siteMapNode title="Spreadsheet"/>
            <siteMapNode title="Word Processor"/>
            <siteMapNode title="Presentation"/>
            <siteMapNode title="Mail"/>
            <siteMapNode title="Games"/>
          </siteMapNode>
          <siteMapNode title="Books" url="Default.aspx?node=books">
            <siteMapNode title="Programming"/>
            <siteMapNode title="Debugging"/>
            <siteMapNode title="Testing"/>
            <siteMapNode title="Web Apps"/>
            <siteMapNode title="WinForm Apps"/>
          </siteMapNode>
        </siteMapNode>
        <siteMapNode title="Services">
          <siteMapNode title="Consulting" url="Default.aspx?node=consulting">
            <siteMapNode title="Processes"/>
            <siteMapNode title="Management"/>
            <siteMapNode title="Recruiting"/>
          </siteMapNode>
          <siteMapNode title="Development" url="Default.aspx?node=development">
            <siteMapNode title="Web Apps"/>
            <siteMapNode title="Enterprise Apps"/>
            <siteMapNode title="Database"/>
          </siteMapNode>
        </siteMapNode>
        <siteMapNode title="Support">
          <siteMapNode title="Drivers" url="Default.aspx?node=drivers">
            <siteMapNode title="Audio"/>
            <siteMapNode title="Network"/>
            <siteMapNode title="Printer"/>
            <siteMapNode title="Modem"/>
          </siteMapNode>
          <siteMapNode title="Manuals" url="Default.aspx?node=manuals">
            <siteMapNode title="Applications"/>
            <siteMapNode title="Troubleshooting"/>
            <siteMapNode title="Installation"/>
            <siteMapNode title="Internet"/>
          </siteMapNode>
          <siteMapNode title="Updates" url="Default.aspx?node=updates">
            <siteMapNode title="Release 1"/>
            <siteMapNode title="Game Package"/>
          </siteMapNode>
        </siteMapNode>
      </siteMapNode>
    </siteMap>
    
  4. Save the file.

Making the First Menu

The first menu displays a single level of static menu items. It is displayed horizontally at the top of the page.

To create the first menu

  1. In Solution Explorer, double-click the Default.aspx page to open it.

  2. Switch to Design view.

  3. From the Navigation control group in the Toolbox, drag a Menu control onto the page.

  4. In the Properties window, set the Orientation property to Horizontal.

  5. Set MaximumDynamicDisplayLevels to 0.

    This ensures that no portions of the menu will appear in a dynamic, fly-out fashion.

  6. Be sure that StaticDisplayLevels is set to 1.

    This allows only one level to appear in the menu.

  7. Click the smart tag on the Menu control.

    The Menu Tasks dialog box appears.

  8. Choose New Data Source in the Choose Data Source drop-down list.

  9. In the Data Source Configuration Wizard, choose Site Map.

  10. Accept the default name of SiteMapDataSource1 and click OK.

Configuring the First Data Source

Because the first menu displays only a single level of static menu items, you need to configure its data source to display the appropriate portion of the Web.sitemap file. In this case, it is the second-level elements: Products, Services, and Support.

The default bindings of the Menu control to a SiteMapDataSource control make each menu item a navigation link. Because you want to programmatically control the behavior of another menu, you use custom bindings so these menu items do not act as navigation links but instead cause a postback to occur so the second menu can be updated.

To configure the first data source

  1. View the Default.aspx page in Design view, and then click the smart tag on the Menu control.

    The Menu Tasks dialog box appears.

  2. Click Edit MenuItem Databindings.

  3. In the Menu DataBindings Editor, in the Available data bindings drop-down list, select SiteMapNode and click Add.

  4. Select TextField in the Data binding properties drop-down list and select Title from the drop-down menu. Click OK.

  5. Select the SiteMapDataSource control.

  6. In Properties, set ShowStartingNode to False.

Creating the Second Menu

The second menu is dynamic, and its data source uses only a portion of the site map file that is determined programmatically by what has been selected on the first menu. Like before, you want the menu to display its first level statically; however, you now want the rest of the Web.sitemap file to appear dynamically.

To create the second menu

  1. View the Default.aspx page in Design view, and then drag a second Menu control onto the page below the first Menu control.

  2. In Properties, set Orientation to Horizontal.

  3. Click the smart tag on the second Menu control.

    The Menu Tasks dialog box appears.

  4. Choose New Data Source in the Choose Data Source drop-down list.

  5. In the Data Source Configuration Wizard, choose Site Map.

  6. Accept the default name of SiteMapDataSource2 and click OK.

Configuring the Second Data Source

In this section, you configure the data source to select only a particular section of the Web.sitemap file. To do this, you start with the default first category in the first menu, which is the Products section of the Web.sitemap file. You then use the StartingNodeURL property to indicate a specific URL attribute within the file.

To configure the second data source's starting point

  1. Select SiteMapDataSource2 and set its StartingNodeURL property to "Default.aspx?node=hardware".

  2. Set StartingNodeOffset to -1.

  3. Set ShowStartingNode to False.

Adding Code to Coordinate the Menus

To control the second menu based on the state of the first menu, catch the MenuItemClick event of the first menu, and indicate the second menu's view of the site map file in code.

To coordinate the menus in code

  1. View the Default.aspx page in Design view and select Menu1.

  2. In Properties, set the MenuItemClick event to Menu1_MenuItemClick.

    A method named Menu1_MenuItemClick will be created for you in the code-behind file for the Default.aspx page, or inside the <script> tags of the .aspx page if you are using the single-file page model.

  3. Add the following highlighted code to the method.

    Protected Sub Menu1_MenuItemClick(ByVal sender As Object, _
      ByVal e As System.Web.UI.WebControls.MenuEventArgs) _
      Handles Menu1.MenuItemClick
      Select Case e.Item.Value
        Case "Products"
          SiteMapDataSource2.StartingNodeUrl = "Default.aspx?node=hardware"
        Case "Services"
          SiteMapDataSource2.StartingNodeUrl = "Default.aspx?node=consulting"
        Case "Support"
          SiteMapDataSource2.StartingNodeUrl = "Default.aspx?node=drivers"
      End Select
    End Sub
    
    protected void Menu1_MenuItemClick(Object sender,    
          System.Web.UI.WebControls.MenuEventArgs e)
    {
      switch(e.Item.Value)
      {
        case "Products":
          SiteMapDataSource2.StartingNodeUrl = "Default.aspx?node=hardware";
          return;
        case "Services":
          SiteMapDataSource2.StartingNodeUrl = "Default.aspx?node=consulting";
          return;
        case "Support":
          SiteMapDataSource2.StartingNodeUrl = "Default.aspx?node=drivers";
          return;
      }
    }
    

    The preceding code catches the click event of Menu1. Instead of navigating to any location, you use the value to determine what the second Menu control displays. You accomplish that by adjusting the StartingNodeUrl property of the second Menu control's SiteMapDataSource control.

  4. Save the file.

Testing the Menus

To test the interaction between the two menus, click items on the first menu, and watch the second menu change accordingly. The second menu is dynamic, and features the third level of the Web.sitemap file.

To test the menu

  1. Press CTRL+F5 to run the page.

    The first menu appears, with the secondary menu featuring the menu items beneath Products in the Web.sitemap file.

  2. Click Services in the first menu.

    The second menu now displays Consulting and Development dynamic menus.

  3. Click Support.

    The second menu displays the Drivers, Manuals, and Updates dynamic menu items.

Next Steps

The Menu control allows you to create navigation menus easily, and offers programmatic support for more complex scenarios. You might also want to experiment with the following options:

See Also

Tasks

Walkthrough: Displaying a Menu on Web Pages

Concepts

Menu Control Overview