Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access body element from content page via a nested master page

Tags:

asp.net

All I want to do is access the <body> element from the code-behind of a content page and add a class name to it.

I have a top-level master page with the <body> element in it. Then I have a nested master page which is the master page for the content page. From the code behind of the content page I want to add a class name to the body element. That's all.

I have this in the top-level master:

<body id="bodyNode" runat="server">

I added this to the code-behind for the content page:

Master.bodyNode.Attributes.add("class", "home-page");

And I get a message that:

System.Web.UI.MasterPage' does not contain a definition for 'bodyNode

If I add this to the aspx content page:

<% @ MasterType VirtualPath="~/MasterPage.master"%>

The message then changes to:

bodyNode is inaccessible due to its protection level

Please advise, I've wasted like 2 hours on what feels like something that should be really simple to do :(

like image 943
danwellman Avatar asked May 19 '10 14:05

danwellman


1 Answers

once you have set runat="server" for your body node, you have to access it using the HTMLControls namespace. try this.

public void Page_Load(Object sender, EventArgs e)
{ 
//Inject onload and unload
HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("bodyNode");
body.Attributes.Add("class", "home-page");   
}

EDIT
Your problem is that you have nested master pages.

Since the "body" tag is in your top level master page, Master.FindControl() won't work, as that is looking in the nested master page.

What you need to do is use Master.Master.FindControl(), or recursively loop through your master pages, going up until Master.Master is null (as then you know you are at the top level master page) and then calling FindControl() on that.

like image 176
Greg Olmstead Avatar answered Oct 14 '22 19:10

Greg Olmstead