我的主页有runat =“server”& Id设置在body标签上。见下文
<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");
但似乎找不到添加atrribute或将inf转换为HtmlGenericControl的方法。
任何帮助都会很棒。
答案 0 :(得分:5)
我不是依赖于母版页类型,而是使用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(...);
}
您甚至可以通过搜索标签名称为“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;
}
答案 1 :(得分:1)
您需要在aspx文件中添加以下内容:
<%@ MasterType VirtualPath="~/Your_Master_Page.Master" %>
然后你可以在页面的.cs上进行操作:
Master.BodyTag.Attributes.Add("class", "NewStyle");
答案 2 :(得分:0)
你正在做的事情似乎有点复杂,可能有更简单的方法来解决这个问题。
要回答您的问题,您不需要使用反射。您只需将传递给FindPage
的参数转换为您创建的母版页类型。
您尚未指定母版页的类型名称,因此我会将其命名为MyMasterPage
。
所以FindPage
应该是这样的:
public static void FindPage(Control mp)
{
var masterPage = mp as MyMasterPage;
if (mp != null)
{
mp.BodyTag.Attributes.Add("class", "NewStyle");
}
}