Hi today I’m going to show you the power of ASP.NET 2.0 Client Callbacks and how could it help us to implement real life Ajax web control.
The main idea to show you how to implement control which will allow you to submit some data without postbacks. It will be CompositeControl consist of
Actually it will be TextBox with button. When you click the button or press the Enter the data from TextBox submit to server and then response from server returns to client where it processed by the client side code.
ToolboxData("<{0}:Register runat=\"server\"> </{0}:Register>"),
public class SearchEdit : CompositeControl, ICallbackEventHandler
private TextBox txtSearch;
private String _ClientClickHandler;
private HtmlInputButton btnSearch;
[Description("Name of Callback ClientScript function with such signature (args, context)")]
public String ClientClickHandler
get { return _ClientClickHandler; }
set { _ClientClickHandler = value; }
private static readonly object EventAsyncClickKey =new object();
[Description("Edit Text")]
EnsureChildControls();
EnsureChildControls();
txtSearch.Text = value;
public string ButtonText
#endregion
//so you can act with it like with a normal Event in your server code
public AsyncArgs(string text)
Text = text;
public delegate void AsyncClickEventHandler(object sender, AsyncArgs e);
Description("Raised when the user clicks the button or press enter.")
Events.AddHandler(EventAsyncClickKey, value);
Events.RemoveHandler(EventAsyncClickKey, value);
protected virtual void OnAsyncClick(AsyncArgs e)
AsyncClick(this, e);
private void RegisterOnClickScript()
if (_ClientClickHandler != string.Empty && _ClientClickHandler != null)
RegisterClientCallbackScript();
btnSearch.Attributes.Clear();
//when we click the button we call client side function SendValue(this)
//it has such look "+ this.ID+"SendValue(this); in the case we
btnSearch.Attributes.Add("onclick", "return "+ this.ID+"SendValue(this);");
StringBuilder sb = new StringBuilder();
sb.Append("function " + this.ID + "SendValue(edt){");
sb.Append(" var name=document.getElementById('" + this.ID + "_" + txtSearch.ID + "').value;");
sb.Append(this.ID+"CallServer(name,'');");
sb.Append("}");
sb.Append("\n");
private void RegisterClientCallbackScript()
string cbReference = m.GetCallbackEventReference(this, "args", _ClientClickHandler, "");
string strCallback = "function "+this.ID+"CallServer(args,context){" + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), this.ID+"CallServer", strCallback, true);
private void RenderControlToCell(HtmlTextWriter writer, Control ctrl)
writer.RenderBeginTag(HtmlTextWriterTag.Td);
ctrl.RenderControl(writer);
writer.RenderEndTag();
protected override void Render(HtmlTextWriter writer)
AddAttributesToRender(writer);
btnSearch.Value = _ButtonText;
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "1", false);
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
RenderControlToCell(writer, txtSearch);
RenderControlToCell(writer, btnSearch);
writer.RenderEndTag();
writer.RenderEndTag();
Controls.Clear();
btnSearch = new HtmlInputButton();
txtSearch = new TextBox();
txtSearch.ID = "txtSearch";
btnSearch.ID = "btnSearch";
//when the user press Enter we don’t want pastback we want to call function SendValue
txtSearch.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + this.ID + "_" + btnSearch.ID + "').click();return false;}} else {return true}; ");
txtSearch.AutoPostBack = false;;
[Description("gets or sets args value wich passes to client script")]
public string CallbackArgs
get { return _CallbackArgs; }
set { _CallbackArgs = value; }
public void RaiseCallbackEvent(string eventArgument)
OnAsyncClick(new AsyncArgs(eventArgument));
Some comments. Our control inherits from CompositeControl and implements ICallbackEventHandler interface. Look to implementation of
|
GetCallbackResult
|
Returns the results of a callback event that targets a control. |
|
RaiseCallbackEvent
|
Processes a callback event that targets a control. |
in the code above.
In web.config we add such piece of code:
<pages>
<controls>
</controls>
</pages>
In Default.aspx such code(I added two controls to show that they can work together):
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<script language="javascript" type="text/javascript">
//this function is callback function which shows the server response
document.getElementById("SearchResult").innerHTML =args;
<myControl:SearchEdit ID="btnedtSearch" runat="server" ClientClickHandler="ShowSearchResult"
OnAsyncClick="btnedtSearch_AsyncClick" Font-Bold="True" Font-Italic="True" Font-Names="Arial Black"
Font-Size="Larger" Width="225px" ButtonText="Search" ></myControl:SearchEdit>
<myControl:SearchEdit ID="SearchEdit1" runat="server" ClientClickHandler="ShowSearchResult"
Font-Bold="True" Font-Italic="True" Font-Names="Arial Black" Font-Size="Larger"
Width="243px" OnAsyncClick="btnedtSearch_AsyncClick" ButtonText="Advanced Search"/>
Then double click to the one of controls in designer and we get in a code behind file something like this:
Let’s do our server side code more realistic.
Server side code
We implement some simple search from file. So we create text file with some .NET SDK words.
Look the code:
protected void Page_Load(object sender, EventArgs e)
protected void btnedtSearch_AsyncClick(object sender, SearchEdit.AsyncArgs e)
searchText = e.Text;
(sender as SearchEdit).CallbackArgs = getFilteredWordsInHtmlFormat();
// this function returns HTML wrapped words that match the search word from client side
protected string getFilteredWordsInHtmlFormat()
Array.Sort(wordList, new CaseInsensitiveComparer());
String[] filteredList = Array.FindAll(wordList, IsMatch);
private static string GetHtmlFromArray(string[] returnValue)
for (int i = 0; i < returnValue.Length; i++)
result += returnValue[i] + "<br>";
result = "<p><b>Search result:</b><br>" + result + "</p>";
private string[] GetWords()
List<String> words = new List<string>();
FileStream file = new FileStream(Server.MapPath("~/App_Data/words.txt"), FileMode.Open,
FileAccess.Read);
StreamReader reader = new StreamReader(file);
file.Close();
//The Predicate that defines the conditions of the elements to search for.
//Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.
private static bool IsMatch(String s)
if (s.ToLower().IndexOf(searchText.ToLower()) >= 0)
So our control is ready to use.
It works without postbacks and was checked in Opera and Firefox.
(?) Kigorw 2006 special for www.ajaxline.com
Hi
I gone thru ur code and it's very gud..I do have small requirement, in this i created composit control lets say grifview in composite control, on input in textbox, this gridview wil b displayed in floating div and on click of row, it populates textbox and make it hidable..this is done till now. But i get stuck, if user doesnot select any row and press esc to hide this..How to implement this..pls do reply..
Sonia, this is very very old example. I'm strongly advice you to write custom javascript without any kind of asp.net controls(which is hard to develop). Use usercontrol with javascript. Look to asp.net MVC and use philosophy of it.
Hi,
I liked your code..and the way it is implemented is also excellent. Can u help me implement the full-text indexing feature of sql 2005? Can it be implemented through stored procedure?I will wait for your reply
thanks and regards
Guria
thanx but actually i need a bit of help in coding for my project ...which is to build up a matrimonial site..and for that i need a search control in which i have to search according to religion and all ...so if u have some simpler coding in Asp.net can u please help me out...
Thanks for mentioning
Zsss
thanx but actually i need a
please send me the tutorial
This tutorial is a really
what will be the code for changing connectionstring for the foll
Hi
Thanks
Thanks for the tip. I
Something big, I'll read it
Please provide me the source code of this aplication.
Creating Search Ajax Web Control in ASP.NET 2.0 using Client Callbacks