Sunday, July 11, 2010

Creating Callback Function In ASP.NET

Creating Callback Function In ASP.NET

The Code Bellow demonstrate how can you create a web server control that uses Ajax like functionality where JavaScript calls server-side code to validate input and
Displays server side validation message using JavaScript alert.

Add a new web server control. I called it GenderControl (it was supposed to do that functionality but it gone wavered) this class implement interface “ICallbackEventHandler” hence two methods namely
1) void RaiseCallbackEvent(string)
2) string GetCallbackResult()


The event OnPreRender () is through call to method RegisterClientScriptInclude() ensures that we include our .js file which contain a method that is get called in the process of this ajaxified validation, Here in the same function the JavaScript method ClientCallback() is created & outputted to page dynamically using RegisterClientScriptBlock() method of Page.ClientScript.

The RenderContents() does the usual task of adding html control I simple added a html input inside div,applied some style to input as
I just wan to test if works fine.

Code in C# file:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace GenderControl
{

[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ServerControl1 : WebControl,ICallbackEventHandler
{
/*to store result of ajaxified request*/
string result;

[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
[Themeable(true)]
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + this.ID + "]" : s);
}

set
{
ViewState["Text"] = value;
}
}

protected override void RenderContents(HtmlTextWriter output)
{
/*container div*/
/*attributes of div*/
output.AddAttribute(HtmlTextWriterAttribute.Id, "Div_"+this.ClientID);
output.RenderBeginTag(HtmlTextWriterTag.Div);

/*simple html input*/
/*attributes of html input*/
output.AddAttribute(HtmlTextWriterAttribute.Type, "text");
output.AddAttribute(HtmlTextWriterAttribute.Id, "GC_"+this.ClientID);
output.AddAttribute(HtmlTextWriterAttribute.Name, "GC_" + this.ClientID);
output.AddAttribute(HtmlTextWriterAttribute.Style, "color:white;background-color:red;font-weight:bold;");
output.AddAttribute(HtmlTextWriterAttribute.Value, this.Text);
output.AddAttribute("onBlur", "ClientCallback(this.value,0)");
output.RenderBeginTag(HtmlTextWriterTag.Input);
/*closing input tag*/
output.RenderEndTag();

/*closing div tag*/
output.RenderEndTag();
}


/*Event Handlers*/
protected override void OnPreRender(EventArgs e)
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "ControlFocus", "document.getElementById('GC_"+this.ClientID+"').focus();", true);

/*************one way of registering script as text****************/
//string strJs = "function ensureNonEmpty(ctl){if(ctl.value.trim() ==''){alert('Please Fill The Required Value');ctl.focus();}}";
//Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "ValidationControl", strJs, true);

/*************Another way register a javascript file**************
*Do not forgot to add reference to assembly first
******************************************************************/
Page.ClientScript.RegisterClientScriptInclude("UtilityFunctions", Page.ClientScript.GetWebResourceUrl(this.GetType(), "GenderControl.scripts.JScript1.js"));

/*Another way out*/
string js = Page.ClientScript.GetCallbackEventReference(this, "args", "ClientCallbackHandler", "ctx", "ErrorHandler", true);

StringBuilder sb = new StringBuilder();
sb.Append("function ClientCallback(args, ctx) {");
sb.Append(js);
sb.Append("}");
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ClientCallBack", sb.ToString(), true);
//Page.ClientScript.RegisterStartupScript(typeof(Page),"ClientCallBack","function ClientCallBack(){args=document.getElementById('GC_" + this.ClientID+ "').value;"+ strT +"}" ,true);
}

public void RaiseCallbackEvent(string eventArgument)
{
if (this.IsInteger(eventArgument))
{
result = "Valid Data";
}
else
{
result = "In-Valid Data";
//throw new Exception("The Method Or Operation Not Implementaed !");
}

}

// Define method that returns callback result.
public string GetCallbackResult()
{
return result;
}

public bool IsInteger(string theValue){
try{
Convert.ToInt32(theValue);
return true;
}
catch
{
return false;
}
}


}


}

Code From ” scripts/Jscript1.js” file

var args;
var ctx;

function ensureNonEmpty(ctl){
if(ctl.value==''){
alert("Field id Mandatory!");
ctl.focus();
}
}
function ClientCallbackHandler(args,ctx)
{
alert(args)
}

function ErrorHandler(args,ctx)
{
alert("Please Enter A Number")
}

In AssemblyInfo.cs add Extra line:

/* assemblname.path.filename is convention that makes string GenderControl.scripts.JScript1.js from bellow line*/

[assembly:System.Web.UI.WebResource("GenderControl.scripts.JScript1.js", "application/x-javascript")]


One More Tweak :
Right click of js file choose property to set build action to embedded resource.
Write click solution and add new website into this site drag and drop control.
The onblur event will fire call server side script there output will be displayed as alert.This can be verified using break point to right positions.

Test Run:
To test run the code run default.aspx modify the code in input type text press tab, you get validation alert depending upon the value entered in html input
If numeric then valid else invalid

No comments:

Post a Comment