Solved

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

Posted on 2010-11-24
9
320 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
Comment Utility
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
Comment Utility
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
Comment Utility
Carl,

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

Question: would this work inside a master page?
0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 5

Author Comment

by:KTN-IT
Comment Utility

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
Comment Utility
I'm headed home for the day.  Happy Thanksgiving!
0
 
LVL 52

Expert Comment

by:Carl Tawn
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks for your help!
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

743 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now