This little quick tip is nothing new or groundbreaking, but I know that when I first started out with .NET it stumped me for a bit. Let’s learn how to select that active navigation item with C# in a master page
This little quick tip is nothing new or groundbreaking, but I know that when I first started out with .NET it stumped me for a bit. Let’s learn how to select that active navigation item with C# in a master page
Here’s the code in my Master Page, nothing too complex, just a simple UL with links. Notice that each link has a unique ID:
<ul> <li><asp:HyperLink runat="server" ID="home" Text="Home" NavigateUrl="/" /></li> <li><asp:HyperLink runat="server" ID="about" Text="About" NavigateUrl="/about" /></li> <li><asp:HyperLink runat="server" ID="about" Text="Contact" NavigateUrl="/contact" /></li> </ul>
Here’s the code from my code behind on my Default.aspx.cs (This page loads the master file mentioned above)
protected void Page_Load(object sender, EventArgs e)
{
var selectedNav = (HyperLink)Master.FindControl("home");
selectedNav.CssClass = "selected";
}
The above code will look through the master page and find the control with the id of “home” and apply the css class of “selected”. You can then target this selected item with CSS to indicate an active page state.
You can use the Master.FindControl to get access to pretty much anything that is in your master page, you’re not limited to Hyperlinks.









One Response
[...] up on my C# Friday quick tip on selecting navigation in master pages with C# .net, here’s another equally slick tip, how to detect an iPhone using [...]