Reputation:
I have a master page masterpage.master
in which i have stored a value in a variable that is
string Name = (string)(Session["myName"]);
Now i want to use the value which is in "Name" into the child pages of masterpage.master
but without using session on every page. Can I achieve that?
If yes..then please tell.
I am using c#
and ASP.net
webforms
Upvotes: 4
Views: 23484
Reputation: 3914
You can try like this:
// Master Page File (Storing the value in label)
string Name = (string)(Session["myName"]);
lblmsg.Text= name;
// cs File
Label str = Master.FindControl("lblmsg") as Label;
TextBox10.Text = str.Text ;
Upvotes: 4
Reputation: 279
Use the masterpagetype directives in your aspx page like below
<%@ MasterType virtualPath="~/Site.master"%>
Now you can access the variables of master page using "Master.[VariableName]"
Upvotes: 1
Reputation: 11464
Add a new Readonly Property to your Master Page
public string MyName
{
get { return (string)(Session["myName"]); }
}
Add this code after your page declaration of content page (change the Master Page file name & path accordingly )
<%@ MasterType virtualpath="~/Site.master" %>
Then you can access your property from the content page
var MyNameFromMaster = Master.MyName;
Upvotes: 2
Reputation: 2167
You can access your masterpage from current page and cast it to your class type:
MyMasterPage master = Master as MyMasterPage;
var value = master.NeededProperity;
Looks like here in MSDN in comments:
Public property is a good way to go, but one would have to put the MasterType directive in every content page (the .aspx file). If content pages extend a base class (which extends Page), then the same strong typing can be done in the base class CodeBehind. For example:
// MySiteMaster : System.Web.UI.MasterPagepublic
string Message
{
get
{
return MessageContent.Text;
}
set
{
MessageContent.Text = value;
}
}
// MyPage : System.Web.UI.Page
MySiteMaster masterPage = Master as MySiteMaster;
masterPage.Message = "Message from content page";
MessageContent is a control on the master page. The MyPage class could expose Message as its own property or allow derived classes to access it directly.
Upvotes: 1
Reputation: 3681
You can put Name
in a control i.e. TextBox
on MasterPage
and find that in content pages like this.
// On Master page
TextBox mastertxt = (TextBox) Master.FindControl("txtMaster");
// On Content Pages
lblContent.Text = mastertxt.Text;
For more details on it check this on MSDN
Upvotes: 3