user2575061
user2575061

Reputation:

Getting values from master page to child page in asp.net

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

Answers (5)

Bhupendra Shukla
Bhupendra Shukla

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

Murugavel
Murugavel

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

Nalaka526
Nalaka526

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

Roar
Roar

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

Mayank Pathak
Mayank Pathak

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

Related Questions