Mark Allison
Mark Allison

Reputation: 7228

ASP.NET how to set text on a master page?

I have a master page called MasterPage.master which has a <fieldset> with a <legend> tag. Something like this:

<fieldset id="NewTrade" runat="server">
    <legend runat="server" class="legend"><%= this.BodyTitle %></legend>
    <asp:ContentPlaceHolder id="contentMain" runat="server" />       
</fieldset>

The masterpage.master file inherits SiteMaster from SiteMaster.cs. SiteMaster has a public field called BodyTitle. I want to set the BodyTitle when a normal page loads but I'm not sure how to do that. Basically all I want to do is have a legend surrounding my master content and then set the legend text at page load time for each page. What's the best way to do that?

So, in say Default.aspx I want to do something like this in Page_Load:

BodyTitle.Text = "Home"

Thanks

Upvotes: 2

Views: 1355

Answers (4)

Delmirio Segura
Delmirio Segura

Reputation: 1691

Save the text in a variable.

public string Heading { get; set; }

Then add the value to this variable from the other page;

(this.Master as Site1).Heading = "Hello"; 

Upvotes: 0

theChrisKent
theChrisKent

Reputation: 15099

(this.Master as SiteMaster).BodyTitle.Text = "Home";

This casts the Master page property of your Page to the base class SiteMaster. You can also cast it directly to the MasterPage class (from your MasterPage.master), but if you are going to do this then @Greg's answer is better, although they will both work. Just depends on your requirements. Setting the MasterType property of the aspx page is a great solution, but if you are doing dynamic switching of your master page or would like to be more flexible, then the above solution would fit better.

Upvotes: 2

Greg
Greg

Reputation: 16680

You can put this at the top of your Content page:

<%@ MasterType VirtualPath="~/masterpage.master" %>

That will automatically cause the Master property of your page to be of the type of your master class, so you can then access the property without casting.

Upvotes: 1

Andrew Barber
Andrew Barber

Reputation: 40150

You would use the Master property of the Page object, and cast it to your SiteMaster class.

((SiteMaster)this.Master).BodyTitle = "Home";

Upvotes: 1

Related Questions