Highlighting Menu Bar in ASP.NET Web Application
I have a Visual Studio 2010 and when I added a NEW project, VS gives me default css and UI themes. I have 6 aspx pages. Now whenever user is going into some specific page, I want the menu bar of that page to get highlighted so that user will know which page he/she is.
I have a page called: CommSetup.aspx. In the page_load I have written this code:
And in the master page I changed this:
In code behind:
protected void Page_Load(object s开发者_StackOverflow社区ender, EventArgs e)
{
foreach (MenuItem item in NavigationMenu.Items)
{
var navigateUrlParams = item.NavigateUrl.Split('/');
if (Request.Url.AbsoluteUri.IndexOf(navigateUrlParams[navigateUrlParams.Length - 1]) != -1)
{
item.Selected = true;
}
}
}
Markup:
<body runat ="server" clientidmode ="Static" id = "MasterBody">
<form runat="server">......
<asp:Menu ID="NavigationMenu" runat="server" StaticSelectedStyle-CssClass ="Selected" CssClass="menu" .....
This is what I added in Site.css:
div.menu ul li a.Selected
{
background-color: #bfcbd6;
color: #465c71;
text-decoration: none;
}
Here's an example of doing exactly what you're asking for using CSS:
http://hicksdesign.co.uk/journal/highlighting-current-page-with-css
You should be able to achieve that using static ID naming on your controls (instead of letting ASP.NET assign the ID value to each control).
EDIT:
To get this to work with a master page, change the <body>
tag in your master page to:
<body runat="server" clientidmode="Static" id="MasterBody">
Then in the Page_Load of each page, you can overwrite the id for each page (the master page in my example is of type SiteMaster
):
protected void Page_Load(object sender, EventArgs e)
{
Control c = Page.Master.FindControl("MasterBody");
if (c != null)
{
c.ID = "Page1";
}
}
Update (2):
I tried running Farzin's example and it didn't seem to work, so here is what I was able to verify worked for me (you won't need the Page_Load
from before in your content pages):
Site.master
<asp:Menu ID="NavigationMenu" ...>
<StaticSelectedStyle CssClass="selected" />
...
</asp:Menu>
Site.master.cs
protected void Page_Load(object sender, EventArgs e)
{
foreach (MenuItem item in NavigationMenu.Items)
{
item.Selected = Page.ResolveUrl(item.NavigateUrl).ToLowerInvariant() == Request.Path.ToLowerInvariant();
}
}
Styles/Site.css
div.menu ul li a.selected
{
/* put your style definition here */
}
You should parse current url in Master page (code behind) and assign different css clss to menu item that belongs to current url.
foreach (MenuItem item in NavigationMenu.Items)
{
var navigateUrlParams = item.NavigateUrl.Split('/');
if(Request.Url.AbsoluteUri.IndexOf(navigateUrlParams[navigateUrlParams.Length - 1]) != -1)
{
item.Selected = true;
}
}
just put this code in Form_Load event of your main master page (code behind)
You could use the ASP.NET Site Navigation functionality. Scott Mitchell has put out one of the definitive articles on it here.
精彩评论