Avi
Avi

Reputation: 137

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.

Upvotes: 3

Views: 86164

Answers (3)

R.Alonso
R.Alonso

Reputation: 1065

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

Upvotes: 0

ACP
ACP

Reputation: 35268

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

or

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

Upvotes: 1

Guffa
Guffa

Reputation: 700382

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.

Upvotes: 16

Related Questions