Displaying alert message from code-behind in ASP.NET

By | August 12, 2013

In this post I will explain how to display alert message in ASP.NET from code-behind. We will create a function in the code-behind file to display alert message dynamically.

We will register Javascript dynamically at runtime using ScriptManager.RegisterStratupScript method and display a Javascript alert message from the code-behind.

Create a new ASP.NET Application and add a Button:
<!DOCTYPE html>

<head runat="server">

    <form id="form1" runat="server">
            <asp:Button ID="bthSayHello" runat="server" Text="Say Hello" onclick="bthSayHello_Click" />

Write following in the code-behind page:
public void Alert(Page page, string message)
    string jsString = "alert('" + message + "');";
    ScriptManager.RegisterStartupScript(page, page.GetType(),

protected void bthSayHello_Click(object sender, EventArgs e)
    Alert(this.Page, "Hello");


Public Sub Alert(ByVal page As Page, ByVal message As String)
  Dim jsString As String = "alert('" + message + "');"
End Sub

Protected Sub bthSayHello_Click(sender As Object, e As EventArgs) Handles bthSayHello.Click
     Alert(Me.Page, "Hello")
End Sub

Using RegisterStartupScript we can write any Javascript code at runtime. But as we only need to display an alert message, we are only passing alert() method with our message string as the script parameter in the RegisterStartupScript method. Now, we have a server-side function “Alert” that can be called with a Page and a string object to display a message at runtime.

2 thoughts on “Displaying alert message from code-behind in ASP.NET

  1. Dave

    Worked great… couldn’t find an example like this anywhere. I wanted to be able to call an alert, pass text and data values to, all from a selectedindexchanged event. This worked like a charm.


Leave a Reply

Your email address will not be published. Required fields are marked *