asp.net从内容页面更改主页面部分css

sd_*_*ula 2 c# asp.net master-pages

我的母版页中有以下代码:

<div id="body" runat="server">
        <asp:ContentPlaceHolder runat="server" ID="FeaturedContent" />
        <section runat="server" id="sectionMainContent" class="content-wrapper main-content clear-fix">
            <asp:ContentPlaceHolder runat="server" ID="MainContent" />
        </section>
    </div>
Run Code Online (Sandbox Code Playgroud)

对于一个特定的内容页面,我想将<section>上面的类值更改为类似的内容class="content-wrapper-full-width main-content clear-fix"

如何<section>从内容页面的代码隐藏中访问属性并修改其值?

Tim*_*ter 5

您可以在master中创建一个公共属性来获取/设置类:

// sectionMainContent is a HtmlGenericControl in codebehind
public String SectionCssClass
{
    get { return sectionMainContent.Attributes["class"]; }
    set { sectionMainContent.Attributes["class"] = value; }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以将主数据转换为正确的类型,并在内容页面中访问此属性:

protected void Page_Init(object sender, EventArgs e)
{ 
    SiteMaster master = this.Master as SiteMaster; // replace with correct type
    if(master != null)
        master.SectionCssClass = "content-wrapper-full-width main-content clear-fix";
}
Run Code Online (Sandbox Code Playgroud)

附注:您可以使用该@Master指令Master在强类型的内容页面中使用该属性.然后你有编译时安全性,你不需要将它转换为实际类型:

在您的内容页面中(替换为实际类型):

<%@ MasterType  VirtualPath="~/Site.Master"%>
Run Code Online (Sandbox Code Playgroud)

现在这可以直接使用:

protected void Page_Init(object sender, EventArgs e)
{
    this.Master.SectionCssClass = "content-wrapper-full-width main-content clear-fix";
}
Run Code Online (Sandbox Code Playgroud)