【问题标题】:Calling method in Master page from User control从用户控件调用母版页中的方法
【发布时间】:2019-02-14 11:34:53
【问题描述】:

我正在构建一个 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 页面上

然后我从用户控件中调用这样的 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)}");

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

【问题讨论】:

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


    【解决方案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);
            }
        }
    }
    

    【讨论】:

    • 这完成了工作 :) 我在基于域的项目中放置了一个静态帮助程序类,并将其命名为“InfoDisplay.DisplayMessage("Test message !!!", "Test title", nameof(ToastrTypeEnum.错误)); " 像魅力一样工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    相关资源
    最近更新 更多