Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a method in a Master Page from a Content Page

I am writing an ASP.NET 4 application with C#. I have a Master Page, inside of which I have the following method:

public void DisplayMessage(string input)
{
   Label myMessageDisplayer = (Label)FindControl("uxMessageDisplayer");
   myMessageDisplayer.Text = input;
}

Can I call this method from a content page?
At the moment, I use in Content Page this code:

Master.DisplayMessage("Item has been inserted.");

And I receive this error:

'System.Web.UI.MasterPage' does not contain a definition for 'DisplayMessage' and no extension method 'DisplayMessage' accepting a first argument of type 'System.Web.UI.MasterPage' could be found (are you missing a using directive or an assembly reference?)

Any help will be appreciated.

like image 578
GibboK Avatar asked Feb 21 '11 16:02

GibboK


2 Answers

You can use casting to get your master page type, as others have shown, or you can add the MasterType directive to your page markup (at the top, where the standard <%@ Page %> directive is):

<%@ MasterType TypeName="YourNamespace.YourMasterPageType" %>

Then in your page code, you can have just what you have in your example:

Master.DisplayMessage("Item has been inserted.");

The MasterType directive is available from .NET 2 upwards.

like image 170
Graham Clark Avatar answered Sep 21 '22 16:09

Graham Clark


You need to cast the Master to the actual Masterpage type

// MyMasterPage is the type of your masterpage
((MyMasterPage)Master).DisplayMessage("Item has been inserted.");

You can also add a MasterType directive to the top of your content page to achieve the same thing:

<%@ MasterType VirtualPath="~/MyMasterPage.master" %>

Then you can use:

Master.DisplayMessage('Item has been inserted.');
like image 25
Geoff Appleford Avatar answered Sep 22 '22 16:09

Geoff Appleford