Wednesday, January 7, 2009

Alert box in ASP.NET from Code behind page

We are aware that JavaScript supports alert box to display information to the user.

When we develop web applications in Asp.Net there could be situations to show message in alert box to user when and there required.
Displaying alert box could be of 2 types.
To explain about this let us consider a form, which is to create a user account and generate user id (system generated).
1) Display alert box using java script in .aspx page
Let us consider validation in a form.
When user clicks on save button with out entering mandatory fields, we display alert box immediately with out post backing page.







Validation for mandatory fields. Checking before submitting the page to server. (Client side validation with alert box)



Validation for numeric validation (Age). Checking before submitting the page to server. (Client side validation with alert box)



2) Display alert box from code behind page
After saving the data provided by user in the form, we may need to display the generated ID after saving the record with an alert box from code behind page.






Displaying alert box from code behind page after the record is saved successfully





To display alert box from code behind page, we can use “IcallbackEventHandler” interface and implement “GetCallbackResult” and “RaiseCallbackEvent” methods.

Please have glance at the source code below.
Please copy below source code into your local machine, to understand comments written against each statement to display alert box from server side and client side
Aspx page:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AlertBox.aspx.cs" Inherits="AlertBox" %>

<!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>Alert box</title>
<script type="text/javascript" language="javascript">
//javascript function to validate user provided data in the forum
function validate(txtName,txtAge)
{
if(document.getElementById(txtName).value.length==0 || document.getElementById(txtAge).value.length==0)
{
alert('All fields are mandatory');
return false;
}
if(!isNumber(document.getElementById(txtAge).value))
{
alert('Age is numeric');
document.getElementById(txtAge).focus();
return false;
}
return true;
}
function isNumber(vl)
{
var nums='1234567890';
var chr='';
for(i=0;i<vl.length;i++)
{
chr=vl.charAt(i);
if(nums.indexOf(chr)==-1)
return false;
}
return true;
}
</script>
<script type="text/javascript" language="javascript">
//Function used by code behind page through ICallBackEventHandler to display
//alert box
function DisplayAlert(response,context)
{
alert(response);
}
</script>
<link href="Styles/Stylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="maintable">
<tr>
<td>Name</td><td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Age</td><td><asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Save</td><td><asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" CssClass="cssbutton" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code behind page :-
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class AlertBox : System.Web.UI.Page,ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Client side validation for mandatory and numeric age (in aspx page)
btnSave.Attributes.Add("onclick", "javascript:return validate('" + txtName.ClientID + "','" + txtAge.ClientID + "');");
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
Alert("Saved sucessfully, ID = 1");
}
public string alertCallBack;
//Alert box from code behind page
void Alert(string strMessage)
{
//This creates a script or method call statement, which calls "DisplayAlert" javascript function available in .aspx page.
//When this script is registered, then "RaiseCallbackEvent" function available in code behind page (method implemented through ICallbackEventHandler)
// is called and response from "GetCallbackResult" function (method implemented through ICallbackEventHandler) is sent as parameter to "DisplayAlert" javascript function available in .aspx page.
//"DisplayAlert" javascript function helps to display alert box in the browser

//This kind of registering script is using Asynchronous javascript technique but not Ajax exactly

alertCallBack = Page.ClientScript.GetCallbackEventReference(this, "'" + strMessage + "'".Replace("\n", " "), "DisplayAlert", "");
string strScript;
strScript = "";
ClientScript.RegisterStartupScript(typeof(Page), "AlertBox", strScript);
}

#region ICallbackEventHandler Members
string strReturnValue;
public string GetCallbackResult()
{
//returning the meesage assigned to strReturnValue variable to DisplayAlert javascript function
return strReturnValue;
}

public void RaiseCallbackEvent(string eventArgument)
{
//Assigning the recieved message to a varaible (strReturnValue) that will be returned by GetCallbackResult function
strReturnValue = eventArgument;
}

#endregion
}

2 comments:

tareq said...

the code is not working..
I am try but the alert box does not appeared.

Can u tell me why?

Anonymous said...

Add this in your code behind:

YourButtonName.Attributes.Add("onclick", "Alert('Displaying alert')");