Click here to Skip to main content
15,884,960 members
Articles / Web Development / ASP.NET

Navigation Menu with XML Datasource (ASP.NET Server Control)

Rate me:
Please Sign up or sign in to vote.
4.13/5 (9 votes)
13 Aug 2008CPOL2 min read 104.5K   2K   41   9
Navigation menu using XML as data source: ASP.NET Server Control

NavigationMenu/menu1.jpg

Introduction

Throughout my Web designing days, I always needed navigation menus with dynamic content which are also easily editable and customizable. Last month, I decided to write a simple menu control which uses CSS to style and uses XML as source for menu items.

Navigation Menu Server Control

XML
<?xml version="1.0" encoding="utf-8" ?>

<menuitems>
  <item id="1" url="Default.aspx" linkname="Main Page"
      description="Main Page of web siter"/>
  <item id="2" url="Default2.aspx" 
  linkname="Company" description="Company Details"/>
  <item id="3" url="Default3.aspx" 
  linkname="Photos" description="Photo Gallery"/>
  <item id="4" url="Default4.aspx" 
  linkname="Contact" description="Contact Form"/>
</menuitems>

This is the XML template for menu items and links.

From the Visual Studio menu, follow the tree: File - New - Project - Web - ASP.NET Server Control, and create a new server control project. By default, ServerControl1.cs is installed. Right click the project and add a new Class called xmlreader.cs In this class, first of all, we define an object that represents menu item. Let's call it menuitem for simplicity's sake.

C#
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.Collections;

public class menuitem
{
    public menuitem() { }
    private string id; //id of item
    private string url; // url for menu link
    private string linkname; //name of the link that will be displayed
    private string description;  // description displayed when mouse hover

    public string Id { get { return id; } set { id = value; } }
    public string Url { get { return url; } set { url = value; } }
    public string Linkname { get { return linkname; } set { linkname = value; } }
    public string Description { get { return description; } 
        set { description = value; } }
}

After defining menuitem, we will create an instance of an arraylist class called getMenu into the xmlreader class. In the getMenu method, we read XML with XLINQ. This method takes two parameters:

  • path
  • xmlFilename
C#
public ArrayList getMenu(string xmlPath, string xmlFileName)
{
    //array List to get menu items from xml
    ArrayList menuitems = new ArrayList();
    try
    {
        XElement xmenu = XElement.Load(xmlPath + xmlFileName);
        if (xmenu != null)
        {
            //get data from xml for menu items using XLINQ
            var xc = from c in xmenu.Elements("item")
            orderby c.Attribute("id").Value
            select new
                {
                ID = c.Attribute("id"),
                URL = c.Attribute("url"),
                LINKNAME = c.Attribute("linkname"),
                DESCRIPTION = c.Attribute("description")
                };
            foreach (var l in xc)
            {
                menuitem itm = new menuitem();
                //item id
                itm.Id = l.ID.Value;
                //menu item url
                itm.Url = l.URL.Value;
                //menu item name
                itm.Linkname = l.LINKNAME.Value;
                //menu description
                itm.Description = l.DESCRIPTION.Value;
                menuitems.Add(itm);
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    //return menu items
    return menuitems;
}

In the above methods, we created an arraylist. Now we have to create our HTML code. To do this, we go to the ServerControl1.cs class.

The menuHtmlGenerator method is the one that takes items in the arraylist, we build with getMenu in xmlreader and creates the markup code for HTML page.

C#
    protected string menuHtmlGenerator(ArrayList aList)
    {
        StringBuilder s = new StringBuilder();
        
        //looping through Arraylist collection of Links.
        for (int i = 0; i < aList.Count; i++)
        {
            s.Append(System.Environment.NewLine);
            
            s.Append("<li >");

            s.Append("<a href ='" + ((menuitem)aList[i]).Url + "' ");
    
            s.Append("title='" + ((menuitem)aList[i]).Description + "' ");
        
            //if menu will show different class for currently selected item
            if (useDiffCssForCrrntItem)
            {
                if (((menuitem)aList[i]).Id == currentItemId)
                s.Append("class='" + currentItemClass + "' ");
            }
    
            s.Append(">");
        
            s.Append("<span>" + ((menuitem)aList[i]).Linkname + "</span> ");
    
            s.Append("</a>");

            s.Append("</li>");

            s.Append(System.Environment.NewLine);
        }
        //Return Full HTML Code As String
        return s.ToString();
    }
}

After generating HTML code, we use a method derived from WebControl. In the method, the first thing we do is declare properties of the menu. They will be used as design-time attributes to customize the control.

C#
public class ServerControl1 : WebControl
{
    #region 7 properties for design-time attritubes

    private string xmlPath; // xml file path
    private string xmlFileName; // xmlfile name
    private string menuClass; // CSS class to ship the menu
    private string menuId;  // main div id that will surround menu
    //  will menu show selected link differently?
    private bool useDiffCssForCrrntItem = false;       
    private string currentItemClass; //currently selected item's class
    private string currentItemId; //id that will determine which item is selected

    #endregion

    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("")]
    [Localizable(true)]
    #region 4 Member properties Used as Design-Time Attributes for 
        Our Server Control

    public string XmlPath { get { return xmlPath; } set { xmlPath = value; } }
    public string XmlFileName { get { return xmlFileName; } 
    set { xmlFileName = value; } }
    public string MenuClass { get { return menuClass; } 
        set { menuClass = value; } }
    public string MenuId { get { return menuId; } 
        set { menuId = value; } }
    public bool UseDiffCssForCrrntItem { get { return useDiffCssForCrrntItem; } 
        set { useDiffCssForCrrntItem = value; } }
    public string CurrentItemClass { get { return currentItemClass; } 
        set { currentItemClass = value; } }
    public string CurrentItemId { get { return currentItemId; } 
        set { currentItemId = value; } }
    #endregion

    //render method. THIS IS MAIN METHOD WHERE ALL THE HTML CODE IS GENERATED AND
    //PASSED TO HTML PAGE

    protected override void RenderContents(HtmlTextWriter output)
    {
        try
        {
            // make instance from Data Class
            xmlreader myData = new xmlreader();
            //Write menu div
            output.Write("<div class='" + menuClass + 
            "' id='" + menuId + "'>");
            //Open Ul Tag
            output.Write("<ul>");
            //write the Links Tag which is returned by GetNew(connectionStr) Method
            //menuHtmlGenerator method is explained below
            output.Write(menuHtmlGenerator(myData.getMenu(xmlPath, xmlFileName)));
            //ul Close Tag
            output.Write("</ul>");
            //div Close Tags
            output.Write("</d i v></div>");
        }
        catch (Exception ex)
        {
            output.Write(ex);
        }
    }

After we build our project in Visual Studio, right click the head of the toolbox and click Choose Items and select DLL file from the bin folder.

NavigationMenu/menu2.jpg

After that, drag and drop the new item to the page. Set the properties. Prepare the XML file which is in the sample project.

Points of Interest

This menu control is a sample of what you can do with server controls. They are powerful and fast.

History

  • 8th August, 2008: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer KuantumSoft
Turkey Turkey
Software Architect

Comments and Discussions

 
GeneralMy vote of 1 Pin
grantdp1-Feb-11 1:57
grantdp1-Feb-11 1:57 
Questionsome improvements? Pin
codeproject@ideabubble.ie20-Jul-09 21:11
codeproject@ideabubble.ie20-Jul-09 21:11 
GeneralGet error when created a example Pin
ColdSun24-Oct-08 7:24
ColdSun24-Oct-08 7:24 
QuestionHow about generating your menu (with the xml Ds) on the client-side? Pin
Guillaume Leparmentier13-Aug-08 22:06
Guillaume Leparmentier13-Aug-08 22:06 
(all is in title)
AnswerRe: How about generating your menu (with the xml Ds) on the client-side? Pin
Enes Gundogmus14-Aug-08 8:52
Enes Gundogmus14-Aug-08 8:52 
GeneralTest project Pin
paulsoren11-Aug-08 10:04
paulsoren11-Aug-08 10:04 
Generalsample xml file for menu Pin
Enes Gundogmus11-Aug-08 10:40
Enes Gundogmus11-Aug-08 10:40 
QuestionRe: Test project Pin
andii567812-Aug-08 2:16
andii567812-Aug-08 2:16 
Answercss sample - images for menu backgrounds are not included. Pin
Enes Gundogmus12-Aug-08 2:22
Enes Gundogmus12-Aug-08 2:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.