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

时间:2019-02-14 11:34:53

标签: asp.net user-controls master-pages toastr

我正在构建一个Web窗体应用程序,我在其中使用JS lib 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页面上

然后我从User Control调用这样的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)}");

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

1 个答案:

答案 0 :(得分:1)

我不完全确定这可以解决您的问题,因为在其他地方使用Control所导致的错误不在您的问题之内。 但是,为什么不将ShowToastr当作静态方法放在单独的类而不是Master中呢?这样,您就不必将Page发送到方法和/或强制转换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);
        }
    }
}