从用户控件调用母版页中的方法

Calling method in Master page from User control

我正在构建一个 Web 表单应用程序,我在其中使用 JS 库 Toastr 向用户显示消息。 这对大多数部分来说都很好用。 我的应用程序是这样设计的

大师 - 嵌套大师 - 页 - 用户控制

我已经在 Master 中实现了对 Toastr 的调用:

public void ShowToastr(Page page, string message, string title, string type = "info")
{
    ScriptManager.RegisterStartupScript(page, page.GetType(), "toastr_message",
        $"toastr.{type.ToLower()}('{message}', '{title}');", addScriptTags: true);
}

我在每个母版页和内容页中都设置了虚拟路径:

Admin.master 文件

<%@ MasterType VirtualPath="~/Areas/Shared/Site.Master" %>

SystemSettings.aspx 页

<%@ MasterType VirtualPath="~/Areas/Administration/Admin.Master" %>

UserCntrol 在 SystemSettings.aspx 页面上

然后我从用户控件中像这样调用 SiteMaster 方法

((SystemSettings)this.Page).Master.Master.ShowToastr(this.Page, "Property successfully updated.", "Success", $"{nameof(ToastrTypeEnum.Success)}");

效果很好....直到我将用户控件放在不同的页面上(希望能够在多个地方使用控件...

在互联网上搜索后,我尝试了几种方法。 .

(this.Page.Master as SiteMaster)?.ShowToastr(this.Page, "Property successfully updated.", "Success", $"{nameof(ToastrTypeEnum.Success)}");

还有

SiteMaster _m = (SiteMaster)Page.Master;


_m.ShowToastr(this.Page, "Unable to save new property", "Error", $"{nameof(ToastrTypeEnum.Error)}");

有人对如何解决这个问题有建议吗??

我不完全确定这是否能解决您的问题,因为在其他地方使用控件所导致的错误不在您的问题范围内。 但是为什么不在单独的 class 而不是 Master 中使 ShowToastr 成为静态方法呢?这样你就不必将 Page 发送到方法 and/or cast the Master.

namespace MyNameSpace
{
    public class Class1
    {
        public static void howToastr(string message, string title, string type = "info")
        {
            Page page = HttpContext.Current.CurrentHandler as Page;
            ScriptManager.RegisterStartupScript(page, page.GetType(), "toastr_message", $"toastr.{type.ToLower()}('{message}', '{title}');", addScriptTags: true);
        }
    }
}