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

独自空忆成欢 提交于 2019-12-12 08:37:05

问题


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.


回答1:


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.




回答2:


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



回答3:


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'?



来源:https://stackoverflow.com/questions/5068521/how-to-use-a-method-in-a-master-page-from-a-content-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!