I have an ASP.NET / C# application in which the Master Page contain the main menu of my application and several content pages that depend of this master page.
I would like to highlight the menu link of my master page corresponding to the current content page displayed.
To do that, I already have a CSS class dedicated to this (called “selected”)
Thus, I was trying to access the Master Page link I want to highlight from the content page by using its ID and do something like that (in the content page) :
HtmlLink currentMenu = (HtmlLink) Master.FindControl("idOfTheLinkToHighlight");
currentMenu.Attributes.Add("class", "selected");
But I get the following exception :
Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlGenericControl' to type 'System.Web.UI.HtmlControls.HtmlLink
Can anybody help me on this ?
Thanks
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
By the way, try
(HtmlGenericControl)currentMenu = (HtmlGenericControl) Master.FindControl("idOfTheLinkToHighlight");
currentMenu.Attributes.Add("class", "selected");
it should work because HtmlGenericControl has also attributes
Method 2
Was messing around with this for a while as I needed it to be a HTML link. Turns out that you need runat=”server” in the e.g.
<head runat="server" id=aHead>
Method 3
Just for a reference, I needed to do something similar and in order to get it working I added the runat=”server” to the body tag (thanks to this thread).
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0