ASP.Net Web Forms - How to set properties of MasterPage from page and user controls
I have two master pages which are used by different content pages. I want to set master page properties from content page, so that master page can show some changes based on those values. And then I also need to access t开发者_开发百科hose master page properties in user controls added in master page to reflect some changes. How to achieve that?
I have found a way how to set master page properties from content page by adding <%@ MasterType VirtualPath="/Site.master" %>
and then using **Master.property=value**
but not sure about how to access user control. Any ideas?
You can create a base class form which your master pages inherit from that includes the properties you're looking to store:
abstract public class MasterPageBase : System.Web.UI.MasterPage
{
public string Prop1
{
get { return "Some Value"; }
}
}
From your UserControl, you can then access the properties as follows:
MasterPageBase masterPage = (MasterPageBase)this.Page.Master;
string strTest = masterPage.Prop1; // "Some Value"
I couldn't get the above answers to work, so here is what worked for me:
You want to reference a master page property from a user control.
Firstly, your master page will have a public property like so :
public string BodyClass
{
set
{
this.masterBody.Attributes.Add("class", value);
}
}
Now add a reference to the master page in the user control ASCX file like so :
<%@ Register Src="~/Source/MasterPages/Main.master" TagPrefix="MSTR" TagName="MasterPage" %>
Then in the code behind (C# in my case) you have this code :
Main masterPage = (Main)this.Page.Master;
masterPage.BodyClass = "container";
Without the reference to the master page above your user control will not be able to find the master page class.
I guess you can access user control defined in your master page in two ways:
By using FindControl method, in order to use this you have to add the server tags for user control in content page too, in .aspx page add this:
<%@ Register Src="~/myControl.ascx" TagName="myControl" TagPrefix"uc" %>
then in code behind:
myControl = (myControl)this.Page.Master.FindControl("userControl_Id");
or you can create a public property in your masterpage that returns your usercontrol:
public myControl UserControl { get; set; }
and in code behind of your content page you can access this user control simply through UserControl property:
myControl ctrl = (myControl)this.Page.Master.UserControl;
The controls is defined in Master.designer.cs with access modifier "protected." Cut and paste its definition to code-behind (Master.cs) and change the access modifier to "public." Then you can access the Master Page control as in the answer given by Derek Hunziker:
MasterPageBase masterPage = (MasterPageBase)this.Page.Master;
string strTest = masterPage.Prop1; // "Some Value"
精彩评论