Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic solution to change navigation id to highlight current page ASP.NET

I am writing a website with Visual Studio 2008 and ASP.NET 3.5. I have a masterpage set up to simplify the layout and to keep the content pages for content rather than content and layout.

The navigation is list, css'd so it looks like a bar. In order to highlight the page on the bar, the list item needs to look like this <li id="current">. I do not want to use <asp:ContentPlaceHolder> if I can avoid it. Is there some code I can add to each of my pages (or just to the masterpage?) to accomplish this or am I stuck using <asp:ContentPlaceHolder>'s?

like image 733
Anders Avatar asked Oct 09 '08 16:10

Anders


2 Answers

Have you considered using a Web.sitemap file? It makes it real easy. If your sitemap file looks like this...

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
  <siteMapNode>
    <siteMapNode url="~/Default.aspx" title="Home"  description="" />
    <siteMapNode url="~/Blog.aspx" title="Blog"  description="" />
    <siteMapNode url="~/AboutUs.aspx" title="AboutUs"  description="" />
  </siteMapNode>
</siteMap>

...then you can do this in your master page to achieve the results you want:

<asp:SiteMapDataSource ID="sitemapdata" runat="server" ShowStartingNode="false"  />
<ul id="navigation">
    <asp:Repeater runat="server" ID="navrepeater" DataSourceID="sitemapdata">
        <ItemTemplate>
            <li class="<%# SiteMap.CurrentNode.Equals(Container.DataItem) ? "activenav" : "inactivenav" %>"><a href="<%# DataBinder.Eval(Container.DataItem, "url") %>"><%# DataBinder.Eval(Container.DataItem, "title") %></a></li>
        </ItemTemplate>
    </asp:Repeater>
</ul>

The current page's LI will have a class of "activenav" (or whatever you decide to use), and the others will have a class of "inactivenav". You can write your CSS accordingly. This is the technique I use on my site and it works great.

like image 86
Joshua Carmody Avatar answered Jan 04 '23 11:01

Joshua Carmody


Add a property to your master page called Page Section

public string PageSection { get; set; }

Add a MasterType page directive to the top of your content pages

<%@ MasterType VirtualPath="~/foo.master" %>

In your content page code behind, set the PageSection property of the master page

Master.PageSection = "home";    

In your master page, make the body tag a server tag

<body ID="bodyTag" runat="server">

In the master page code behind, use that property to set a class on the body tag

bodyTag.Attributes.Add("class", this.PageSection);

Give each of your nav items a unique ID attribute.

In your css, change the display of the nav items based on the current page class

.home #homeNavItem,
.contact #contactNavItem
{ 
    color: #f00; 
} 
like image 35
John Sheehan Avatar answered Jan 04 '23 12:01

John Sheehan