In this article I will explain how to display JavaScript Alert Message Box from server side when using AJAX UpdatePanel in ASP.Net.
Cause
ClientScript.RegisterClientScriptBlock and ClientScript.RegisterStartupScript methods for registering JavaScript code from server side do not work when AJAX UpdatePanel is used in ASP.Net and hence the registered JavaScript is never executed. The reason is that both these methods RegisterClientScriptBlock and RegisterStartupScript do not support Partial PostBack.
Solution
The solution to this problem is to make use of ScriptManager’s RegisterClientScriptBlock and RegisterStartupScript methods as they support Partial PostBack and hence the JavaScript is registered as well as executed.
HTML Markup
The HTML Markup consists of ASP.Net AJAX Script Manager Control, an UpdatePanel and a Button which when clicked will show a JavaScript Alert Message Box
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button Text="Show Message" runat="server" OnClick="ShowMessage" />
</ContentTemplate>
</asp:UpdatePanel>
Code Behind
Inside the Button Click event handler, I have made use of ScriptManager.RegisterClientScriptBlock methods to register a JavaScript alert message box.
C#
protected void ShowMessage(object sender, EventArgs e)
{
string message = "alert('Hello! Mudassar.')";
ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true);
}
VB.Net
Protected Sub ShowMessage(sender As Object, e As EventArgs)
Dim message As String = "alert('Hello! Mudassar.')"
ScriptManager.RegisterClientScriptBlock(TryCast(sender, Control), Me.GetType(), "alert", message, True)
End Sub
Demo
Downloads