• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 356
  • Last Modified:

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
0
KTN-IT
Asked:
KTN-IT
  • 5
  • 4
2 Solutions
 
Carl TawnSystems and Integration DeveloperCommented:
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.
0
 
Carl TawnSystems and Integration DeveloperCommented:
Sample user control:
// markup
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MenuBar.ascx.cs" Inherits="WebApplication1.MenuBar" %>
<ul id="menu">
    <asp:Literal ID="MenuLiteral" runat="server" />
</ul>

// code-behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    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 = "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

0
 
KTN-ITAuthor Commented:
Carl,

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

Question: would this work inside a master page?
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
Carl TawnSystems and Integration DeveloperCommented:
Yes. You just need to register the control in your master page with something like:

<%@ Register Src="~/MenuBar.ascx" TagName="Menu" TagPrefix="mvp" %>

Open in new window

Then add an instance of the menu to your master page:
<mvp:Menu ID="MainMenu" runat="server" />

Open in new window


After that you just need to style it and add whatever menu items you want to the collection.
0
 
KTN-ITAuthor Commented:

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

0
 
KTN-ITAuthor Commented:
I'm headed home for the day.  Happy Thanksgiving!
0
 
Carl TawnSystems and Integration DeveloperCommented:
You'll need to adjust the namespaces in the markup to match your own, and the path to the ASCX file too probably.
0
 
KTN-ITAuthor Commented:
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

0
 
KTN-ITAuthor Commented:
Thanks for your help!
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now