Search code examples
c#asp.netscreenalertresponse.write

How to don't make screen blink when use Response.Write


I want to show an alert on my Web page. I used Response.Write by using a try catch block. When it shows the alert, the page gets white, then after I click okay on the alert box, the page come back. I want the page to stay unchanged and the alert to be shown. How can I make this? This is my C# code.

    protected void ImageSave_Click(object sender, ImageClickEventArgs e)
    {
        SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
        cnn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cnn;

        cmd.CommandText =
                    "insert into BranchMst(SaupCode,BranchCode, BranchName, UseFlag, SeqNo) values ("
                    + "'" + comboSaup.SelectedValue 
                    + "','" + txtBranchCode.Text.TrimEnd()
                    + "','" + txtBranchName.Text.TrimEnd()
                    + "','" + txtSeqNo.Text.TrimEnd()
                    + "')";
        try
        {
            int ret = cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            Response.Write("<script> alert('Error.Please check your ID');history.back(); </script>");
        }
        cnn.Close();

        ReflashData_Grid1();
        ClearField();
    }

Solution

  • This looks like a Web browser rendering issue, not a server issue. If you block the rendering process, such as with your blocking alert method, the render engine can't process the other HTML and script statements. Consequently, you need to call your message box asynchronously.

    Haven't tested, but this may work:

    Response.Write("<script>setTimeout(alert(\'Error.Please check your ID\');history.back();', 200)</script>");
    

    Anyway, rethink how you call data layers and how to deal with exceptions. They are not supposed to be used for business workflows.