gpt4 book ai didi

c# - 反射将 css 类添加到 body 标记 c#

转载 作者:行者123 更新时间:2023-12-03 20:47:36 26 4
gpt4 key购买 nike

我的母版页在 body 标签上设置了 runat="server"和 Id。见下文

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

母版页后面的代码我添加了以下代码:

    public HtmlGenericControl BodyTag
{
get { return MasterPageBodyTag; }
set { MasterPageBodyTag = value; }
}

现在我想将 css 类添加到 App_code 文件夹中 Class1.cs 文件中的 body 标签。

在 .aspx 上使用以下代码传递母版页控件:

  protected void Page_Load(object sender, EventArgs e)
{
backend.FindPage((PageTemp)this.Master);

}

现在在 Class1.cs 上我有以下内容

  public static void FindPage(Control mp)
{

Page pg = (Page)HttpContext.Current.Handler;


PropertyInfo inf = mp.GetType().GetProperty("BodyTag");

我想在找到的 BodyTag 中添加以下内容

 //      BodyTag.Attributes.Add("class", "NewStyle");

但似乎找不到添加属性或将 inf 转换为 HtmlGenericControl 的方法。

任何帮助都会很棒。

最佳答案

我不依赖母版页类型,而是简单地使用 FindControl 按 Id 搜索正文元素。假设 body 标签在您的顶级母版页上,并且假设您可能正在使用嵌套母版页,它看起来像这样:

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(...);
}

您甚至可以通过搜索标签名称为“body”的 HtmlGeneric 控件来移除对 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;
}

关于c# - 反射将 css 类添加到 body 标记 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9618046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com