I am building a web forms application where I user the JS lib Toastr for displaying messages to the user. This works great ...for most parts. My application is designed like this
Master - Nested Master - Page - User Control
I Have implemented the calling to Toastr in Master:
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);
}
I have virtual path set in every master and content page:
Admin.master file
<%@ MasterType VirtualPath="~/Areas/Shared/Site.Master" %>
SystemSettings.aspx page
<%@ MasterType VirtualPath="~/Areas/Administration/Admin.Master" %>
The UserCntrol is on SystemSettings.aspx page
Then I call the SiteMaster method like this from User Control
((SystemSettings)this.Page).Master.Master.ShowToastr(this.Page, "Property successfully updated.", "Success", $"{nameof(ToastrTypeEnum.Success)}");
This works great....until I put the User Control on a different page (want to be able to use controls in more then one place. .
I have tried several things after a search on the internet. .
(this.Page.Master as SiteMaster)?.ShowToastr(this.Page, "Property successfully updated.", "Success", $"{nameof(ToastrTypeEnum.Success)}");
also
SiteMaster _m = (SiteMaster)Page.Master;
_m.ShowToastr(this.Page, "Unable to save new property", "Error", $"{nameof(ToastrTypeEnum.Error)}");
Anyone with a suggestion on how to resolve this??
I'm not entirely sure this fixes your issue because the resulting error of using the Control elsewhere is not in your question.
But why not make ShowToastr
a static method in a separate class and not the Master? That way you do not have to send the Page
to the method 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);
}
}
}