问题
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
回答1:
By the way, try
(HtmlGenericControl)currentMenu = (HtmlGenericControl) Master.FindControl("idOfTheLinkToHighlight");
currentMenu.Attributes.Add("class", "selected");
it should work because HtmlGenericControl has also attributes
回答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>
回答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).
来源:https://stackoverflow.com/questions/1301904/access-an-html-control-on-asp-master-page-from-the-code-behind-of-a-content-page