通过嵌套母版页从内容页访问body元素 [英] Access body element from content page via a nested master page

查看:165
本文介绍了通过嵌套母版页从内容页访问body元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有我想要做的就是访问<车身方式> 从内容页面的code隐藏元素,并添加一个类名给它

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.

我与℃的顶级大师页面;在它元素;车身过夜。然后,我有一个嵌套的母版页这是内容页的母版页。从内容页面背后的code我想一个类名添加到body元素。这就是全部。

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.

我有这样的顶级高手:

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

我已将此添加到code-背后的内容页:

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

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

和我得到的消息是:

System.Web.UI.MasterPage'不包含定义'bodyNode

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

如果我将它添加到的ASPX页面内容:

If I add this to the aspx content page:

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

然后,该消息更改为:

The message then changes to:

bodyNode无法访问由于其保护级别

bodyNode is inaccessible due to its protection level

请指教,我已经浪费了如2个小时什么感觉喜欢的事,应该是很简单的事:(

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

推荐答案

一旦设置=服务器为您的身体节点上,你必须使用HTMLControls命名空间来访问它。试试这个。

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.

由于身体的标签在你的顶层母版页, Master.FindControl()将无法正常工作,因为这是寻找在嵌套母版页。

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.

您需要做的是用 Master.Master.FindControl()或递归遍历你的母版页,往上走,直至主。主为空(如那么你知道你是在顶层母版页),然后调用的FindControl()这一点。

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.

这篇关于通过嵌套母版页从内容页访问body元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆