Click here to Skip to main content
11,434,799 members (47,697 online)
Click here to Skip to main content

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

, 13 Aug 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Navigation menu using XML as data source: ASP.NET Server Control
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 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.

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
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.

    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.

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.

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)

Share

About the Author

Enes Gundogmus
Software Developer KuantumSoft
Turkey Turkey
Software Architect

Comments and Discussions

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

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150428.2 | Last Updated 13 Aug 2008
Article Copyright 2008 by Enes Gundogmus
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid