This tutorial will explain you how to display Message Box / Alert Box in ASP.Net using C# and VB.Net
we will use here a class file (Alert.cs) that can be used in ASP.Net web pages where you want to display Message Box.
Create a new Class file under App_Code folder of your application.
using System.Web; using System.Web.UI; /// <summary> /// Summary description for Alert /// </summary> public class Alert { public Alert() { /// <summary> /// A JavaScript alert /// </summary> /// <param name="message">The message to appear in the alert.</param> } public static void show(string message) { // Cleans the message to allow single quotation mark. string strCleanMessage = message.Replace("'", "\'"); string script = "<script type='text/javascript'>alert('" + strCleanMessage + "');</script"; // Gets the executing web page Page page = HttpContext.Current.CurrentHandler as Page; // Check if the handler is a page and that the script is not already on the page if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) { page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script); } } }
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="VC.aspx.cs" Inherits="VC" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Alert Box in ASP.Net</title> </head> <body> <form id="form1" runat="server"> <asp:Button ID="btnShowMessage" runat="server" Text="Show Message" onclick="btnShowMessage_Click" /> </form> </body> </html>
using System; public partial class VC: System.Web.UI.Page { protected void btnShowMessage_Click(object sender, EventArgs e) { Alert.show("Hello World"); } }
Partial Class VB Inherits System.Web.UI.Page Protected Sub btnShowMessage_Click(sender As Object, e As System.EventArgs) Handles btnShowMessage.Click Alert.show("Hello World") End Sub End Class