我有一个masterpage,它在body标签上设置了runat ="server"和Id.见下文
<body id="MasterPageBodyTag" runat="server">
Run Code Online (Sandbox Code Playgroud)
母版页上的代码我添加了以下代码:
public HtmlGenericControl BodyTag
{
get { return MasterPageBodyTag; }
set { MasterPageBodyTag = value; }
}
Run Code Online (Sandbox Code Playgroud)
现在我想将css类添加到App_code文件夹中Class1.cs文件的body标签中.
在.aspx上使用以下代码传递母版页控件:
protected void Page_Load(object sender, EventArgs e)
{
backend.FindPage((PageTemp)this.Master);
}
Run Code Online (Sandbox Code Playgroud)
现在在Class1.cs上我有以下内容
public static void FindPage(Control mp)
{
Page pg = (Page)HttpContext.Current.Handler;
PropertyInfo inf = mp.GetType().GetProperty("BodyTag");
Run Code Online (Sandbox Code Playgroud)
}
我想在发现的BodyTag中添加以下内容
// BodyTag.Attributes.Add("class", "NewStyle");
Run Code Online (Sandbox Code Playgroud)
但似乎无法找到添加atrribute或将inf转换为HtmlGenericControl的方法.
任何帮助都会很棒.
我不是依赖于母版页类型,而是使用FindControl来按Id搜索body元素.假设body标签位于顶级Master页面上,并且假设您可能正在使用嵌套母版页,则它看起来像:
private static MasterPage GetTopLevelMasterPage(Page page)
{
MasterPage result = page.Master;
if (page.Master == null) return null;
while(result.Master != null)
{
result = result.Master;
}
return result;
}
private static HtmlGenericControl FindBody(Page page)
{
MasterPage masterPage = GetTopLevelMasterPage(page);
if (masterPage == null) return null;
return masterPage.FindControl("MasterPageBodyTag") as HtmlGenericControl;
}
private void UpdateBodyCss()
{
HtmlGenericControl body = FindBody(this);
if(body != null) body.Attributes.Add(...);
}
Run Code Online (Sandbox Code Playgroud)
你甚至可以通过搜索HtmlGeneric标签名为"body" 的控件来删除对id的依赖:
private static HtmlGenericControl FindBody(Page page)
{
MasterPage masterPage = GetTopLevelMasterPage(page);
if (masterPage == null) return null;
foreach(Control c in masterPage.Controls)
{
HtmlGenericControl g = c as HtmlGenericControl;
if (g == null) continue;
if (g.TagName.Equals("body", StringComparison.OrdinalIgnoreCase)) return g;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)