Search code examples
c#asp.netwebformshttpcontextscriptmanager

Navigate to a new page and display an alert box


I am developing an application by using ASP.Net WebForm. Once user click a button, application will navigate to a new page and prompt out a dialog box "Welcome to JackiesGame"

However, I able to navigate to new page but the alert dialog box does not display.

The following is my sample code

void cmdCancel_Click(object sender, EventArgs e)
{
    HttpContext.Current.Response.Redirect(Globals.NavigateURL(TabId), true);
    Page page2 = HttpContext.Current.CurrentHandler as Page;
    ScriptManager.RegisterStartupScript(page2, page2.GetType(), "alertMessage", "alert('Insert Successfully')", true);
}

Solution

  • Add the following in page 2. On the page load it will register only for the first time the page loads the script.

    protected void Page_Load(object sender, EventArgs e)
    {
       if(!Page.IsPostBack)
       {
        var reg = Request["Welcome"]
           if(reg != null && reg.ToString() == "yes"){
              ScriptManager.RegisterStartupScript(this, this.GetType(), "alertMessage", "alert('Insert Successfully')", true);
          }
       }
    }
    

    All code after the redirect is getting ignored since it has to redirect to a new page. So the code never gets triggered.

    EDIT Added a example of how it can look further

    void cmdCancel_Click(object sender, EventArgs e)
    {
        string myUrl = Globals.NavigateURL(TabId)+"?Welcome=yes";
        HttpContext.Current.Response.Redirect(myUrl, true);
    }