.NET Show Javascript alert programmatically

  • by
.NET Show Javascript alert programmatically 02

.NET Show Javascript alert programmatically or code behind.

At times, we require to display a error message or Information message to the users at run time in a alert message.

To display Javascript alert message in .net from code behind use the following code :

ClientScript.RegisterClientScriptBlock(this.GetType(), “alert”, “<script>alert(‘Your message to display.’);</script>”);

in your respective method. The “alert” specifies the heading of your alert message and “Your message to display” specifies the message body text.

Now let’s see the code implementation in a .net website Project.
I’m using a existing .net website project, you can create your own or make a seperate website for this one.
Make a new page with name Default.aspx (if it is not already being created) and edit its design page and code page as below.
This is a simple page containing two elements. .Net textbox and .Net button. On clicking on button our method will fire and show the contents of the textbox will be shown in javascript alert message box.

.NET Show Javascript alert programmatically 01

Default.aspx :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Javascript Alert Programmatically.</title>
 <style>
 body
 {
 font-family: Arial;
 }
 </style>
</head>
<body>
 <form id="form1" runat="server">
 <h1>
 Javascript Alert Programmatically.</h1>
 <h3>
 Enter the text in the Textbox below and click on 'Show Alert' button to display
 alert message.</h3>
 <hr />
 <div>
 <asp:TextBox runat="server" ID="txtMessage" TextMode="MultiLine" Height="70px" Width="700px" />
 <br />
 <br />
 <asp:Button runat="server" ID="btnShow" Text="Show" onclick="btnShow_Click" />
 </div>
 </form>
</body>
</html>

Edit the code file as below.

Default.aspx.cs :

using System;
 using System.Configuration;
 using System.Data;
 using System.Linq;
 using System.Web;
 using System.Web.Security;
 using System.Web.UI;
 using System.Web.UI.HtmlControls;
 using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
 using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page 
 {
  protected void Page_Load(object sender, EventArgs e)
  {

}
  protected void btnShow_Click(object sender, EventArgs e)
  {
  ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "<script>alert('" + txtMessage.Text.ToString() + "');</script>");
  }
 }

Now run your website. The message will be shown on clicking the button.

.NET Show Javascript alert programmatically 02

 


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.