In this article I will explain with an example, how to display
MessageBox using
JavaScript in ASP.Net with C# and VB.Net.
HTML Markup
The HTML Markup consists of following controls:
TextBox – For capturing user input.
Button – For displaying MessageBox.
The Button has been assigned with an OnClick event handler.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Name:</td>
<td><asp:TextBox ID="txtName" runat="server" /></td>
</tr>
<tr>
<td>City:</td>
<td><asp:TextBox ID="txtCity" runat="server" /></td>
</tr>
<tr>
<td>Country:</td>
<td><asp:TextBox ID="txtCountry" runat="server" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSave" Text="Save" runat="server" OnClick="Save" /></td>
</tr>
</table>
Displaying MessageBox when user submits the Form
When the Save Button is clicked, a message is set and StringBuilder class object is created.
message – The message to be displayed in the
JavaScript Alert
MessageBox.
Here, StringBuilder class object is used to create a script (in HTML) for Alert message.
Finally, the
StringBuilder class object is passed as parameter to
RegisterStartupScript method of
ClientScript class which ultimately displays the
JavaScript Alert
MessageBox.
C#
protected void Save(object sender, EventArgs e)
{
//Insert record here.
string message = "Your details have been saved successfully.";
StringBuilder sb = new StringBuilder();
sb.Append("<script type='text/javascript'>");
sb.Append("window.onload = function(){ alert('");
sb.Append(message);
sb.Append("');");
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", sb.ToString());
}
VB.Net
Protected Sub Save(ByVal sender As Object, ByVal e As EventArgs)
'Insert record here.
Dim message As String = "Your details have been saved successfully."
Dim sb As StringBuilder = New StringBuilder()
sb.Append("<script type='text/javascript'>")
sb.Append("window.onload = function(){ alert('")
sb.Append(message)
sb.Append("');")
sb.Append("</script>")
ClientScript.RegisterStartupScript(Me.GetType(), "SuccessMessage", sb.ToString())
End Sub
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads