4

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

Mayank Pathak
  • 3,621
  • 5
  • 39
  • 67
  • passing data between web user control page and master page https://stackoverflow.com/questions/1028937/how-can-i-get-the-parent-page-from-a-user-control-in-an-asp-net-website-not-web/54412216#54412216 – Stewart Nov 22 '19 at 23:37

5 Answers5

4

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 ;
Bhupendra Shukla
  • 3,814
  • 6
  • 39
  • 62
3

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

Mayank Pathak
  • 3,621
  • 5
  • 39
  • 67
1

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.

Roar
  • 2,117
  • 4
  • 24
  • 39
1

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;
Nalaka526
  • 11,278
  • 21
  • 82
  • 116
1

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

Murugavel
  • 269
  • 1
  • 2
  • 9