Access body element from content page via a nested

2020-07-10 08:14发布

问题:

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 :(

回答1:

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.



回答2:

I would add a public property to the code behind of the master page that would allow access to the body tag that is part of the master page. And then call that property from the content page.



标签: asp.net