【问题标题】:How do I call a method in a Master Page from a content's code-behind page?如何从内容的代码隐藏页面调用母版页中的方法?
【发布时间】:2011-06-13 15:54:25
【问题描述】:

我的 ASP.NET 母版页中有一个公共方法。是否可以从内容页面调用它,如果可以,步骤/语法是什么?

【问题讨论】:

    标签: c# asp.net master-pages


    【解决方案1】:

    Page 中,您可以将Master 页面强制转换为特定类型(您自己的Master 类型,它公开了所需的功能),使用as 来绕过类型不匹配的任何异常:

    var master = Master as MyMasterPage;
    if (master != null)
    {
        master.Method();
    }
    

    在上面的代码中,如果Master 不是MyMasterPage 类型,那么master 将是null,并且不会尝试任何方法调用;否则它将按预期调用。

    【讨论】:

    • 先看看Uwe Keim的回答;我发现它使用起来非常简单。
    【解决方案2】:

    使用MasterType directive,例如:

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

    那么你可以使用这样的方法:

    Master.Method();
    

    【讨论】:

      【解决方案3】:

      你可以简单地做...

      MasterPageClassName MasterPage = (MasterPageClassName)Page.Master;
      MasterPage.MasterMethod();
      

      查看详情ACCESS A METHOD IN A MASTER PAGE WITH CODE-BEHIND

      【讨论】:

      • 你能把它作为静态成员添加到页面顶部吗?
      【解决方案4】:
      MyMasterPageType master = (MyMasterPageType)this.Master;
      master.MasterPageMethod();
      

      【讨论】:

      • 你能把它作为静态成员添加到页面顶部吗?
      • 不是静态成员,因为母版页特定于当前处理请求的页面。不过,您可以为母版页创建一个实例属性:private MyMasterPageType master { get { return (MyMasterPageType)this.Master; } }
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多