Link to home
Start Free TrialLog in
Avatar of KTN-IT
KTN-ITFlag for United States of America

asked on

How do avoid repetitive code for color-changing horizontal navigation bar?

I have started on my first ASP.NET (3.5) website using C# in Visual Studio 2010.  This is actually an internal web application for our company. I have some experience programming, but I'd like to ask you experts for your ideas on how to go about the following task.  Points awarded to all helpful responses.

My site has a site.master page which puts the banner across the top.  My question is about how to code a horizontal navigation bar that I'd like to put across the top just below the banner.  It would basically be a horizontal row of boxes to click on much like the one here on EE that says "Browse All, Microsoft, Apple, Digital Living, etc."

Taking advantage of ASP, I don't want to have to put the code for this navbar in every single page of the site.  But I do want the color of "selected" navbar item (the one that matches the currently displayed part of the site) to be different from the others.  (See attached image)

The site has a master page, so I thought about adding a content page just for the navbar.  But I don't know how I would get the nav bar items to change color based on what's being displayed in the content page beneath it.

Or I thought about adding code to App_Code that gets called from each page, with a parameter for which page is being displayed below it so it can render that item a different color.
Clipboard01.gif
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Personally I would implement it (and have done in the past) as a UserControl. You basically have the control draw out a list of menu items (usually as an inline UL) and have it check the page requested in the url to determine the current page and set a css class on it.
SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of KTN-IT

ASKER

Carl,

Thanks for the quick response and for the great piece of code.

Question: would this work inside a master page?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of KTN-IT

ASKER


I'm trying to run your code.  I'm getting a very vague compile error:

Error      1      Could not load type 'WebApplication1.MenuBar'.      

See the default page below I'm trying to test this with.  It says "element 'Menu' is not a known element."  but I'm not sure it's related to the error.

Is there something I have to do in web.config to get this to work?  I'm just using a generic one now.
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/MenuBar.ascx" TagName="Menu" TagPrefix="mvp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <mvp:Menu id="mymenu" runat="server">
    
    </mvp:Menu>
    </div>
    </form>
</body>
</html>

Open in new window

Avatar of KTN-IT

ASKER

I'm headed home for the day.  Happy Thanksgiving!
You'll need to adjust the namespaces in the markup to match your own, and the path to the ASCX file too probably.
Avatar of KTN-IT

ASKER

Here's what I got to work.  Does not include the CSS needed to change the color of the selected item, but I can figure that out.  I removed the namespace declaration entirely.  Also, cannot figure out why the 'class="selected"' is not appended when the site is first loaded (I'm just debugging on my local machine with Visual Studio development server), only during subsequent loads of 'Default.aspx'

Also, for the MenuItems, I had to remove the ~/ from the front of the Urls for them to work correctly for some reason.
<!-- Put this code in Default.aspx -->
<%@ Page Title="Home Page" Language="C#"  AutoEventWireup="true" %>
<%@ Register Src="~/WebUserControl.ascx"  TagPrefix="mvp" TagName="Menu" %>
<html>
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <h2>
        Welcome!
    </h2>
    <p>
        <mvp:Menu ID="MainMenu" runat="server" />
        Put content here
    </p>
</body>
</html>

Open in new window

<!-- Create user control: WebUserControl.ascx -->
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="MenuBar" %>
<ul id="menu">
    <asp:Literal ID="MenuLiteral" runat="server" />
</ul>

Open in new window

//Put this code in code behind: WebUserControl.ascx.cs
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;

public partial class MenuBar : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<MenuItem> menuItems = new List<MenuItem>()
            {
                new MenuItem() { DisplayName = "Default", Url = "Default.aspx" },
                new MenuItem() { DisplayName = "Home", Url = "Home.aspx" },
                new MenuItem() { DisplayName = "About", Url = "About.aspx" }
            };

        DrawMenu(menuItems);
    }

    private void DrawMenu(List<MenuItem> items)
    {
        string currentPage = System.IO.Path.GetFileName(Request.Url.AbsoluteUri);
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        foreach (MenuItem item in items)
        {
            sb.Append("<li");

            if (item.Url.EndsWith(currentPage))
                sb.Append(" class=\"selected\"");

            sb.AppendFormat("><a href=\"{0}\">{1}</a></li>", item.Url, item.DisplayName);
        }

        MenuLiteral.Text = sb.ToString();
    }
}

public class MenuItem
{
    public string DisplayName { get; set; }
    public string Url { get; set; }
    public bool Selected { get; set; }
}

Open in new window

Avatar of KTN-IT

ASKER

Thanks for your help!