Does a MasterPage know what page is being displayed?

Anders picture Anders · Oct 9, 2008 · Viewed 26.8k times · Source

When I navigate on a website utilizing MasterPages, does the application know what page I am on? If so, does it store it in an object I can access?

The reason I am asking is so I can replace this:

//masterpage 
<div id="nav_main">
   <ul><asp:ContentPlaceHolder ID="navigation" runat="server">                    
   </asp:ContentPlaceHolder></ul>
</div>

//content page(s)
<asp:Content ContentPlaceHolderID="navigation" ID="theNav" runat="server">
   <li><a href="default.aspx">Home</a></li>
   <li id="current"><a href="faq.aspx">FAQ</a></li>
   <li><a href="videos.aspx">Videos</a></li>
   <li><a href="#">Button 4</a></li>
   <li><a href="#">Button 5</a></li>
</asp:Content>

With a more elegant solution for the navigation, which highlights the link to the page by having the list item's ID set to "current". Currently each page recreates the navigation with its respective link's ID set to current.

Answer

Blumer picture Blumer · Oct 9, 2008

I'd concur with Chris: use a control to handle display of this menu and make it aware of what link should be highlighted. Here's a method I use regularly. It may become more complex if you've got multiple pages that would need the same link styled differently, but you get the idea.

Dim thisURL As String = Request.Url.Segments(Request.Url.Segments.Count - 1)
Select Cast thisUrl
   Case "MenuItem1.aspx"
       lnkMenu1.CssClass = "Current"
   Case "MenuItem2.aspx"
       lnkMenu2.CssClass = "Current"
End Select