Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » Site Navigation in ASP.NET 2.0

Site Navigation in ASP.NET 2.0

Site navigation uses the layered architecture. Controls such as Menu and TreeView provide the navigation UIs. Classes such as SiteMap and SiteMapNode provide the API.

Technologies: .NET 2.0, ASP.NET 2.0,Visual C# .NET
Total downloads :
Total page views :  1648
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor


Related EbooksTop Videos


Introduction

All of the web applications developed usually have more than one page and they are usually interconnected via some mechanism. In ASP.Net 1.x, navigation was made possible by using hyperlinks with the help of include file or user controls. They are pretty handy but not so much when the pages are moved around or their names change.

So in order to overcome this drawback, ASP.Net 2.0 introduces the new Site Navigation System. Site navigation uses the layered architecture. Controls such as Menu and TreeView provide the navigation UIs. Classes such as SiteMap and SiteMapNode provide the API that the controls rely on and also constitute an API you can use yourself if you wish. Site navigation is provider-based, and the one site map provider that comes with ASP.NET 2.0 -> XmlSiteMapProvider -> reads site maps from XML data files. By default, those files are named Web.sitemap. In the providers' lab, students write a custom site map provider that reads site maps from a SQL Server database.

SiteMap1.gif

Lets us discuss each on of them one at a time.

Site Map in ASP.Net 2.0

Site Maps help us define the layout of all the pages in the application and their inherent relation with each other. For this, one could either use the SiteMap Class or the SiteMapDataSource control.

SiteMapDataSource controls use site map providers to read site maps. They then provide the site map data to the controls they're bound to. Binding a TreeView to a SiteMapDataSource transforms each node in the site map into a TreeView node; binding a Menu to a SiteMapDataSource transforms each node in the site map into a menu item. The only site map provider that comes with ASP.NET 2.0 is XmlSiteMapProvider. It enables site maps to be read from XML files that conform to a predefined schema.

Take up the following steps to create a site map ->

  1. Start Visual Studio 2005 IDE.
  2. Create a new ASP.Net website using C# as language on file system.
  3. Right Click on solution and add a new item. From the Add item Wizard, add a new site map. Let the name be Web.sitemap (default name)
  4. Add the following code to it:-

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
<siteMapNode title="Home" description="Login Page" url="Home.aspx">
<siteMapNode title="Admin" description="Administration Functionalities" url="Admin/AdminHome.aspx">
<siteMapNode title="Create User" description="Create User" url="Admin/CreateUser.aspx"/>
<siteMapNode title="Manage Roles" description="Create/Delete Roles" url="Admin/CreateRoles.aspx"/>
<siteMapNode title="Assign Roles" description="Re-Assign Roles" url="Admin/ManageRoles.aspx"/>
</siteMapNode>
<
siteMapNode roles="" title="Search" description="Search Employee" url="Personal/Search.aspx"/>
</siteMapNode>
</
siteMap>

Only one <sitemap> element can be there in the site map file and there can be multiple <siteMapNode >  element within the root node i.e. <sitemap>

Within the <siteMapNode> element, we have following attributes->

  • Title -> This is actual description which appears as a hyperlink.
  • Description -> Tool Tip which comes up when we hover over that particular siteMapNode.
  • url -> this is the file located within the solution. It can be located within the root folder or within a sub-folder created within the solution.
  • Role -> the roles to which the links should be accessible.

"Security trimming" refers to SiteMapDataSource's ability to hide nodes from users who lack proper authorization. Authorization is role-based and is enacted by including roles attributes in <siteMapNode> elements. Of course, you can use ASP.NET 2.0 Role Management service to define roles and map users to roles. Security trimming is disabled by default in XmlSiteMapProvider. You can enable it by including these statements in Web.config.

<configuration>
  <system.web>
    <siteMap>
      <providers>
        <remove name="AspNetXmlSiteMapProvider" />
        <add name="AspNetXmlSiteMapProvider"
          type="System.Web.XmlSiteMapProvider, System.Web, ..."
          securityTrimmingEnabled="true"
          siteMapFile="web.sitemap" />
      </providers>
    </siteMap>
  </system.web>
</configuration>

Tree View Server control

This is a new server control that has been added to ASP.Net 2.0. It can be used to display the hierarchy of the links contained within the site map file. Once, the Web.sitemap is created, drag and drop a SiteMapDataSource control on the form. It automatically binds it self to web.sitemap file. Then, drop a treeView control on the form and set the DataSource id to SiteMapDataSource1 as shown in the figure below ->

SiteMap2.gif

As soon as you specify the data source id, the structure gets populated in the tree view control. One can go about changing the look and the feel of the tree view control using Auto Format and from the property window of the control.

Every element that appears as a part of tree view control is called as a node. The top-most element or node is called as the root node and any nodes that appear under the root node as referred to as child nodes. The node that does not have any elements under it is called as the leaf node.

SiteMap3.gif

XMLDataSource Control

It is also possible to bind a Tree View control to an XML file. For this, you need to create an XML file and populate the tree view control from the XML file.

As an example, let's create an XML file having a structure something below:-

<?xml version="1.0" encoding="utf-8" ?>
<Controls>
      <
Item Category="Server Controls">
            <Option Choice="Tree view"/>
            <Option Choice="Menu Control"/>
      </Item>
</
Controls>

Then, drag and drop an XmlDataSource control on the form and set the data source to the xml file you just created. Click on Ok once done.

SiteMap4.gif

Then, drag and drop a tree view control on the form and specify the data source id to be the XmlDataSource1 that you have placed on the form configured to use xml file.
If you notice, the tree view control gets populated and renders something below:-

SiteMap5.gif

If you look at the above results, nodes display names of the actual XML elements from the file itself. You need to specify how to bind to the XML file with the use of the <DataBindings> element within the tree view control.

The < DataBindings>, element encapsulates one or more TreeNodeBinding objects. DataMember and TextField are two important properties available within the TreeNodeBinding object. The DataMember refers to the name of the XML element that control should look for and the TextField specifies the XML attribute within the particular XML element. So it should be ->

<asp:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1" ShowLines="True">
<DataBindings>
 <
asp:TreeNodeBinding DataMember="Controls" Text="New Controls"/>
 <asp:TreeNodeBinding DataMember="Item" TextField="Category" />
 <asp:TreeNodeBinding DataMember="Option"    TextField="Choice" />                  
 </DataBindings> </asp:TreeView>

By default, when you run the above application the tree view controls renders the data elements as expanded. If you wish that they should appear collapsed on the page load event, and should be expanded on user action, then add the DataBound event wired up with the Tree View control as

SiteMap6.gif

       protected void TreeView1_DataBound(object sender, EventArgs e)
         {
             TreeView1.CollapseAll();
         }


Once collapsed, you can expand it back on the click of the button having the following code:-

 protected
void Button1_Click(object sender, EventArgs e)
   {
       TreeView1.ExpandAll();
   }

It is also liley possible that you might not only be using the TreeView control for navigation, but also for making certain user selection. For this, the TreeView control provides a functionality where-in the check boxes can be put up against the items. All you need to do for this, is to go to the properties of the tree View control and set the ShowCheckBoxes property to leaf. By default, it is set to none

SiteMap7.gif

This could also be done programmatically by simple code of line ->


TreeView1.ShowCheckBoxes = TreeNodeTypes.Leaf;

Once done, you can loop through the TreeView to return the items that have been selected by the user as stated below:-

foreach (TreeNode node in TreeView1.CheckedNodes)
            {
                Label1.Text += node.Text ;
            }

Site Map API

The SiteMap and SiteMapNode classes provide the API used by SiteMapPath controls. If desired, you can use this API yourself to manually read site maps or even to build site map path controls of your own. System.Web.SiteMap represents site maps ->

  • RootNode property identifies root node
  • CurrentNode property identifies current node
  • SiteMapNode represents nodes

  // Write the title of the current node to a Label control
        Label1.Text = SiteMap.CurrentNode.Title;
        // Write the path to the current node to a Label control
        SiteMapNode node = SiteMap.CurrentNode;
        StringBuilder builder = new StringBuilder(node.Title);
        while (node.ParentNode != null)
        {
            node = node.ParentNode;
            builder.Insert(0, " > ");
            builder.Insert(0, node.Title);
        }

        Label1.Text = builder.ToString();

The first statement in this example retrieves the text of the current node from SiteMap.CurrentNode.Title and displays it by writing it to a Label control. The remaining statements output the path to the current node. Each node in the path is separated by a greater-than sign.

Other Server Controls

a. Menu Server Control

Using the Menu server control is very similar to Tree View control. All you need to do is to drag and drop a SiteMapDataSource control on the form and bind the menu server control to the SiteMapDataSource. One can apply styles via the property window associated with the menu server control.

This control should be used when there are a lot of options to select from. It could be navigation points or the selections that the user can make.

b. SiteMapPath Control

This control creates a navigation hierarchy what is sometimes referred to as Bread crumb navigation. The SiteMapPath control does not need a data source. All one needs is to drag and drop a SiteMap path control onto the page and you all have the results at your disposal. You can change the properties such as the depth of the hierarchy and styles.

Conclusion

Site Navigation is a feature that you further exploit upon owing to great functionality that it offers. The article does not delve deeply into the menu server control for site navigation but underlying mechanism is the same as the tree view control.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Anubhav Bansal
Anubhav Bansal is a Microsoft Certified Application Developer(MCAD) and Microsoft Certified Technology Sepcialist and has been working in Microsoft Technologies for more than 5 years. Anubhav has extensive experience in developing web based applications and client -server applications. For past 1 year, Anubhav has been working on developing Online Service Delivery applications using Windows Communication Foundation. Also equipped with the knowledge on MVP(Model viewer Presentation) design pattern and thread safe singleton patterns.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved