Tuesday, March 13, 2012

Set properties on masterpage declaratively

Hi, is it possible to do this?

So you'd set a property on the master page in the aspx.

If by declaratively you mean programmatically, yes you can. Take a look at my example

I created a MasterPage, called BasePage.master, and added the following code to its code-behind:

public partialclass BasePage: System.Web.UI.MasterPage{private int magicNumber;public int MagicNumber {get {return magicNumber; }set { magicNumber =value; } }protected void Page_Load(object sender, EventArgs e) { }}

Then I created a new Web Form (.aspx) page, called Test.aspx, and picked Base.master to be its MasterPage. I also added the following line to .aspx page:

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

Using the MasterType directive allows the .aspx page to access the public properties and fields of the MasterPage via the Master property. The following code is from the code-behind of Test.aspx, take a look:

public partialclass Test : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e) { Master.MagicNumber = 2007; }}

Hope this helps.


Hi there, I appreciate your effort but since when has doing something declaratively ever meant writing code in a code behind file?? I mean, isn't the whole point of the word 'declarative' to indicate the absence of code?


Hi,

Your original question wasn't clear, as in you didn't say whether or not you had created the property on the Master page or not. Don't scold someone for trying to help you!

If you just need to set an existing property on the master page declaratively, then use the following code (for a string property):

<%Page.Master.MyProperty = "MyValue"%>

Of course though, if the property doesn't already exist on the Master Page, then youMUST write code to create it! For this, refer to the above post for instructions.

Rich


Yes my question was not that clear.

<%Page.Master.MyProperty = "MyValue"%>

The trouble with this is that its a render block so its not going to be set until the end of the page life cycle. I want to set the value of properties on the master page as if the master page was a user control contained by the page and the assignments are within the user control's tag.

Cheers, WT.


Hi,

Now I see what you mean! I don't think there is a way to do this directly. You are gonna have to write some code initially, but you should be able to reuse it on all pages using the same Master Page. The way I would do it would be to create a User Control and:

Expose a public property on the User Control, taking the value of the property you wish to set.

0 comments:

Post a Comment