AjaxValidator Example, AjaxValidator Control in ASP.Net C#

Like the CustomValidator control, the AjaxValidator control enables to create a custom server-side validation function. Unlike the CustomValidator control, however, the AjaxValidator control enables to call the custom validation function.

The AjaxValidator control uses AJAX (Asynchronous JavaScript and XML) to call the server-side validation function from the client. The advantage of using AJAX is that no postback to the server is apparent to the user.

Example : Imagine that you are creating a website form and you need to validate a User Name field. You want to make sure that the User Name entered does not already exist in the database. The AjaxValidator enables you to call a server-side validation function from the client to check whether the User Name is unique in the database.

AjaxValidator.cs

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace myControls
{

public class AjaxValidator : BaseValidator, ICallbackEventHandler
{
public event ServerValidateEventHandler ServerValidate;
string _controlToValidateValue;
protected override void OnPreRender(EventArgs e)
{
String eventRef = Page.ClientScript.GetCallbackEventReference(this,““,““,““);

String includeScript =Page.ResolveClientUrl(“~/ClientScripts/AjaxValidator.js”);
Page.ClientScript.RegisterClientScriptInclude(“AjaxValidator”,includeScript);

String startupScript = String.Format(“document.getElementById(‘{0}’).evaluationfunction = ‘AjaxValidatorEvaluateIsValid’;”, this.ClientID);
Page.ClientScript.RegisterStartupScript(this.GetType(),“AjaxValidator”, startupScript, true);
base.OnPreRender(e);
}


protected override bool DetermineRenderUplevel()
{
return Context.Request.Browser.SupportsCallback;
}

public string GetCallbackResult()
{
return ExecuteValidationFunction(_controlToValidateValue).ToString();
}

public void RaiseCallbackEvent(string eventArgument)
{
_controlToValidateValue = eventArgument;
}

protected override bool EvaluateIsValid()
{
string controlToValidateValue = this.GetControlValidationValue
(this.ControlToValidate);
return ExecuteValidationFunction(controlToValidateValue);
}

private bool ExecuteValidationFunction(String controlToValidateValue)
{
ServerValidateEventArgs args = new ServerValidateEventArgs
(controlToValidateValue, this.IsValid);
if (ServerValidate != null)
ServerValidate(this, args);
return args.IsValid;
}
}
}

The control inherits from the BaseValidator class. It also implements the ICallbackEventHandler interface. The ICallbackEventHandler interface defines two methods that are called on the server when an AJAX request is made from the client.
In the OnPreRender() method, a JavaScript include file and startup script are registered. The JavaScript include file contains the client-side functions that are called when the AjaxValidator validates a form field on the client. The startup script associates the clientside AjaxValidatorEvaluateIsValid() function with the AjaxValidator control. The client-side validation framework automatically calls this JavaScript function when performing validation.

AjaxValidator.js


function AjaxValidatorEvaluateIsValid(val)
{
var value = ValidatorGetValue(val.controltovalidate);
WebForm_DoCallback(val.id, value, AjaxValidatorResult, val,
AjaxValidatorError, true);
return true;
}

function AjaxValidatorResult(returnValue, context)
{
if (returnValue == ‘True’)
context.isvalid = true;
else
context.isvalid = false;
ValidatorUpdateDisplay(context);
}

function AjaxValidatorError(message)
{
alert(‘Error: ‘ + message);
}

AjaxValidator Control in ASP.Net ASPXThe AjaxValidatorEvaluateIsValid() JavaScript method initiates an AJAX call by calling the WebForm_DoCallback() method.

<%@ Page Language=”C#” %>
<%@ Register TagPrefix=”custom” Namespace=”myControls” %>
<%@ Import Namespace=”System.Data.SqlClient” %>
<%@ Import Namespace=”System.Web.Configuration” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>

protected void AjaxValidator1_ServerValidate(object source,ServerValidateEventArgs args)
{
if (UserNameExists(args.Value))
args.IsValid = false;
else
args.IsValid = true;
}
>
private bool UserNameExists(string userName)
{
if username found in database return "true" else return "false"
}
return result;
}

protected void btnSubmit_Click(object sender, EventArgs e)
{

}
</script>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Demo AjaxValidator</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label id=”lblUserName” Text=”User Name:” AssociatedControlID=”txtUserName” Runat=”server” />
<asp:TextBox id=”txtUserName” Runat=”server” />
<custom:AjaxValidator id=”AjaxValidator1” ControlToValidate=”txtUserName” Text=”User name already taken!” OnServerValidate=”AjaxValidator1_ServerValidate” Runat=”server” />
<asp:Button id=”btnSubmit” Text=”Submit” Runat=”server” OnClick=”btnSubmit_Click” />
</div>
</form>
</body>
</html>
Tags: , ,
Hot on Web:

About author