ASP.NET:通过UserControl在MasterPage中调用函数

Nie*_*sma 6 c# asp.net master-pages asp-usercontrols

从页面中的MasterPage调用函数是非常困难的,但我如何为UserControl调用它:

添加<%@ MasterType VirtualPath="~/MasterPage.master" %>,不适用于UserControls.

所以this.Page.Master.MyFunction()失败:(

JDu*_*ley 12

您必须首先强制转换this.Page.Master ,因为Page 的Master属性是System.Web.UI.MasterPage类型.

例如

((MyMaster)this.Page.Master).MyFunction();
Run Code Online (Sandbox Code Playgroud)

您可以通过向用户控件后面的代码添加属性来检查基础母版页的类型:

    public string MType
    {
        get { return this.Page.Master.GetType().FullName; }
    }
Run Code Online (Sandbox Code Playgroud)

并在用户控件标记中打印结果,例如添加此行以使其在源代码中作为注释打印出来:

<!-- <%= MType %> //-->
Run Code Online (Sandbox Code Playgroud)


Sea*_*ugh 7

尼尔斯,

杠杆反射(由JDunkerley建议)是解决问题的一种方法.您可能考虑的另一个是实现一个接口:

  1. 创建包含方法的界面.
  2. 在主页面中实现界面
  3. 从您的控件,this.Page.Master通过接口类型引用.
  4. 打电话给你的方法

这是一种更好的OO方法,可以减少耦合,并且肯定比运行时反射更好.

我希望这有帮助!