Solved

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

Posted on 2010-11-24
9
336 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

734 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