Part 148 Passing data from content page to master page in asp net04:33

  • 0
Published on October 24, 2017

Text version of the video

Slides

All ASP .NET Text Articles

All ASP .NET Slides

ASP.NET Playlist

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic

This is continuation to Part 147, please watch Part 147 before proceeding.

Let us understand how to pass data from a content page to a master page, with an example.

In the example below,
1. We have a textbox in the master page. The ID of the textbox is “txtBoxOnMasterPage”
2. On the Content page, we have another textbox and a Button. The ID of this textbox is “TextBox1” and the ID of the button is “Button1”
3. When you type some text in the textbox on the content page and when you hit “Set Text” button, we want to display the text entered in the textbox on the content page in the textbox that is present in the master page.

In the code-behind file of the master page, include a public property that returns the textbox control. Content pages will use this property to set the text of the textbox on the master page.
// The property returns a TextBox
public TextBox TextBoxOnMasterPage
{
get
{
// Return the textbox on the master page
return this.txtBoxOnMasterPage;
}
}

Retrieve the master page associated with the content page using Master property and typecast to the actual master page and then reference the property.
protected void Button1_Click(object sender, EventArgs e)
{
// Retrieve the master page associated with this content page using
// Master property and typecast to the actual master page and then
// reference the property
((Site)Master).TextBoxOnMasterPage.Text = TextBox1.Text;
}

If you want Master property to return a strongly typed reference of the associated master page, include the MasterType directive on the content page.

Once you have included the above MasterType directive on the content page, you will now have a strongly typed reference of the master page and can access it’s properties without having to typecast.
protected void Button1_Click(object sender, EventArgs e)
{
Master.TextBoxOnMasterPage.Text = TextBox1.Text;
}

To retrieve a master page associated with a content page, we can use either
1. Master propery
2. Page.Master property

Page.Master property always returns an object of type “MasterPage” and we need to explicitly typecast it to the actual master page, if we need to access it’s properties and methods, where as Master property returns a strongly typed reference of the actual master page if the content page has “MasterType” directive specified. Otherwise “Master” property works in the same way as “Page.Master” property.

Enjoyed this video?
"No Thanks. Please Close This Box!"