Solved

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

Posted on 2010-11-24
9
327 Views
Last Modified: 2012-08-13
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
Comment
Question by:KTN-IT
  • 5
  • 4
9 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 34209284
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
 
LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 500 total points
ID: 34209345
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
 
LVL 5

Author Comment

by:KTN-IT
ID: 34209378
Carl,

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

Question: would this work inside a master page?
0
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 34209390
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
 
LVL 5

Author Comment

by:KTN-IT
ID: 34209484

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
 
LVL 5

Author Comment

by:KTN-IT
ID: 34209493
I'm headed home for the day.  Happy Thanksgiving!
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 34209509
You'll need to adjust the namespaces in the markup to match your own, and the path to the ASCX file too probably.
0
 
LVL 5

Author Comment

by:KTN-IT
ID: 34222672
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
 
LVL 5

Author Closing Comment

by:KTN-IT
ID: 34239138
Thanks for your help!
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question