将css类添加到body标签c的反射#
我有masterat有runat =“server”&设置在body标签上的Id。见下文背后将css类添加到body标签c的反射#
<body id="MasterPageBodyTag" runat="server">
代码对母版我已经添加以下代码:
public HtmlGenericControl BodyTag
{
get { return MasterPageBodyTag; }
set { MasterPageBodyTag = value; }
}
现在我想CSS类在App_Code文件夹Class文件添加到身体标记。
在我的.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的方法。
任何帮助将是伟大的。
而不是依赖于主页类型,我只是使用FindControl来se Id为body元素的拱形。假设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(...);
}
你甚至可以通过搜索的消除对ID的依赖性HtmlGeneric
标签名称为“body”的控件:
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;
}
这对我有用。我尝试使用解决方案@ http://www.codeproject.com/Articles/19386/Adding-attributes-to-the-lt-body-tag-when-using-Ma,但无法让它工作。 – James 2013-11-13 21:09:02
我用这个和标签工作,但什么可能是导致控件和ContentPlaceHolder形式的原因甚至不会加载页面源? – hsobhy 2016-01-28 22:59:16
是更specifec,我实际上使用了一个名为_Culture与继承System.Web.UI.Page的类中的解决方案,然后我在aspx页面调用这个像公共类_Default Inherits _Culture – hsobhy 2016-01-28 23:04:19
你在做什么似乎有点复杂,可能有更简单的方法来解决这个问题。
要回答你的问题,你不需要使用反射。您可以简单地将您传递给FindPage
的参数转换为您创建的主页类型。
您尚未指定您的母版页的类型名称,因此我将其命名为MyMasterPage
。
所以FindPage
应该是这样的:
public static void FindPage(Control mp)
{
var masterPage = mp as MyMasterPage;
if (mp != null)
{
mp.BodyTag.Attributes.Add("class", "NewStyle");
}
}
你需要添加的aspx文件如下:
<%@ MasterType VirtualPath="~/Your_Master_Page.Master" %>
,然后你可以在你的页面的.cs做:
Master.BodyTag.Attributes.Add("class", "NewStyle");
难道你不能用jQuery或类似的方法在客户端实现吗? – 2012-03-08 13:02:12
这是否有用? http://www.codeproject.com/Articles/95438/Changing-A-Master-Page-Body-Tag-s-CSS-Class-for-Di – Rawling 2012-03-08 13:09:25