2

I have the following code in my master page:

<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>

For one specific content page I would like to change the class value of the <section> above to something like class="content-wrapper-full-width main-content clear-fix"

How can I access the <section>'s attributes from codebehind of the content page and modify its value?

1
  • have you added <%@ MasterType virtualpath="~/YourMasterPage.master" %> in your Content Page ? Commented Jan 31, 2014 at 9:12

2 Answers 2

5

You can create a public property in your master which gets/sets the class:

// sectionMainContent is a HtmlGenericControl in codebehind
public String SectionCssClass
{
    get { return sectionMainContent.Attributes["class"]; }
    set { sectionMainContent.Attributes["class"] = value; }
}

Now you can cast the master to the correct type and access this property in your contentpage:

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";
}

Side-note: you can use the @Master directive to use the Master property in your content-page strongly typed. Then you have compile time safety and you don't need to cast it to the actual type:

In your content-page(replace with actual type):

<%@ MasterType  VirtualPath="~/Site.Master"%>

Now this works directly:

protected void Page_Init(object sender, EventArgs e)
{
    this.Master.SectionCssClass = "content-wrapper-full-width main-content clear-fix";
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think you could use the FindControl() method from code behind with something like :

((HtmlGenericControl)Master.FindControl("FeaturedContent")).attributes["class"] = "content-wrapper-full-width main-content clear-fix";

3 Comments

This also worked but just had to change the HtmlElement to HtmlGenericControl
You also have to use attributes["class"] since a HtmGnericControl has no CssClass property. (HtmlElement is a winforms control)
Both thanks for your comments, I improved my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.