简体   繁体   中英

How to popup a Alert on Button Click from code behind in Asp.net 2.0?

I tried this code but is not working ..

protected void btnAbc_Click(object sender, EventArgs e)
{
    string script = "<script language='javascript'>alert('abc');</script>";"
    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script,true);
}

Pls advice.

You have double script tags. Add the script tags yourself:

protected void btnAbct_Click(object sender, EventArgs e) {
   string script = "<script type=\"text/javascript\">alert('abc');</script>";
   ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
}

Or let the method add it:

protected void btnAbct_Click(object sender, EventArgs e) {
   string script = "alert('abc');";
   ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true);
}

Not both.

Also consider if the RegisterStartupScript method is a better fit for what you want to do.

ScriptManager.RegisterStartupScript(this, this.GetType(), "alerts", "javascript:alert('hai')", true); 

or

string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);

By sample. Add a SHARED CLASS, insert this code, and use always in aspx.

In Class Shared (or no)

    Public Shared Sub MostrarAlertaconControl(Control As Control, ByVal pagina As System.Web.UI.Page, ByVal mensaje As String)
    System.Web.UI.ScriptManager.RegisterClientScriptBlock(Control, pagina.GetType(), "alerta", "alert('" & mensaje.Replace("'", """") & "')", True)
End Sub

how call in a .aspx:

    Protected Sub Button1_Click1(sender As Object, e As EventArgs) Handles BotonExportar.Click
    If GridView1.Rows.Count > 0 Then
        Response.Redirect("VistaDatos.aspx")
    Else

        clsUtiles.MostrarAlertaconControl(BotonExportar, Page, "No hay datos para exportar")

    End If

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM