简体   繁体   中英

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.

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.

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.');

I made/try this:

My Control (MenuEsquerdo.ascx)

<%--<%@ MasterType VirtualPath="~/Site.Master" %>--%>
<%--<%@  MasterPageFile="~/Site.Master" %>--%>
<%--<%@ MasterType TypeName="Delivery.SiteMaster" %>--%>
<%--<%@ MasterType VirtualPath="~/Site.Master" %>--%>
<%@ MasterType TypeName="Delivery.SiteMaster" %>

My Designer Control (MenuEsquerdo.ascx.designer.cs)

public new Delivery.SiteMaster Master {
            get {
                return ((Delivery.SiteMaster)(base.Master)); // 'System.Web.UI.UserControl' does not contain a definition for 'Master'
            }
        }

And my code behind (MenuEsquerdo.ascx.cs)

RepeaterListaMenuEsquerdoCtr.DataSource = this.Master.ClassMercadorias.Take(20);
RepeaterListaMenuEsquerdoCtr.DataBind();

Know, how I can fix this: 'System.Web.UI.UserControl' does not contain a definition for 'Master'?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM