Access an HTML control on ASP Master Page from the code behind of a Content Page

做~自己de王妃 提交于 2019-12-12 07:24:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!