从用户控件调用主页面中的方法

问题描述 投票:1回答:1

我正在构建一个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)}");

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

asp.net user-controls master-pages toastr
1个回答
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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.