I would like to structure a menu bar in ASP.NET using the asp:Menu control and master pages.
The feature I am having trouble implementing is to have the menu item for the "current page" display in a style that is distinctive from all of the other menu items.
I have seen a few solutions for this that suggest something like this...
Put a unige ID or Class attribute on the <body> tag of each page referenced in the menu. e.g. <body ID="Home"...> <body ID="Contact"...> etc.
Put a unique ID on each <a> tag in the menu (or a class attribute on the <li> tag). e.g.
<ul id="navbar">
<li><a id="home_link" href="home.htm">HOME</a></li>
<li><a id="contact_link" href="contact.htm">CONTACT</a></li>
</ul>
Create the following CSS...
body#home a#home_link,
body#contact a#contact_link
{ color: #000; background: #fff; } /* or whatever unique attributes are desired */
I have two problems with implementing this...
Since the <body> tag is in the Master page I don't know how to set a unique ID on the <body> tag for each page.
Both the <li> and <a> tags are generated from the asp.MenuItem so I don't see how to apply either an ID or a Class attribute.
If necessary I could forgo using the asp:menu control and just use simple HTML, but I would prefer to use the asp:menu control if that is possible. Even if I do resort to simple HTML (i.e. <ul> <li> <a> etc) for that part of the puzzle, I would really like to continue using a Master page.
This seems like a VERY common way to configure a menu so I am assuming there must be some sort of solution.
On page load in the code behind we build our menu and store an Identifer for each page in the menu item values. We then compare those item values with the name of the page we are currently on to work out which menu item we want to look differently. We then set the selected property on that menu item.
Code:
using System;
using System.Web.UI.WebControls;
namespace TestWebApplication
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Create menu items as store the path/name for each
MainMenu.Items.Add(new MenuItem("Page 1", "~/Page1.aspx"));
MainMenu.Items.Add(new MenuItem("Page 2", "~/Page2.aspx"));
MainMenu.Items.Add(new MenuItem("Page 3", "~/Page3.aspx"));
//Work out what page we are viewing
string pageViewed = this.Page.AppRelativeVirtualPath;
//Go through each menu item and work out which one we want to
//select
foreach (MenuItem item in MainMenu.Items)
{
if (pageViewed == item.Value)
{
item.Selected = true;
}
}
}
}
}
In this example, I have stored the actual page names but I normally use an enumerator and a lookup to a list of page names to make it easier to decouple the naming of the actual pages with the code for setting the menu items.
Last edited by RedBully; April 15th, 2011 at 05:51 AM.
Reason: Type
Bookmarks