المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : How to implement Client Callback in ASP.net without using ASP.net AJAX?



bahattab
05-06-2009, 02:11 AM
How to implement Client Callback in ASP.net without using ASP.net AJAX?



Targeted Audience
This article is intended for ASP.net 2.0 developers who has a basic know how of AJAX.

AJAX (Asynchronous JavaScript And XML) is the programming techniques which are used to build highly interactive web applications. For using the AJAX we need to install the AJAX framework and use the controls like the UpdatePanel, ClientScriptManager etc.

What is a Client Callback?
Client Callback is a feature which allows calling of the server side functions through client side (JavaScript) functions without a causing a postback.

What is a Postback?
It’s a mechanism of communicating the server form client side. In a postback the whole of the page will be send to the server and the EventTarget handler will be executed and the whole new page will be send back.

So we have AJAX which helps us to avoid whole of the page to send to the server for processing and there by giving a rich user experience.

Before getting into any other, let see how users used to have the Asynchronous kind of behavior before the AJAX came.

It all started with the introduction of iframe. iframe is an html tag which helps in having an inline frame which in turn can link to another URL.

<iframe src ="/Results.aspx" width="100%"></iframe>


Using the iframe the web developers came up with the partial refresh of the page literally.

Later came the XMLHttpRequest object from Microsoft which was introduced with its IE ver5, by this a new Web development technique named Ajax came into picture.

What is XMLHttpRequest?

XMLHttpRequest is a JavaScript API which can be used to communicate with the server asynchronously. It uses certain methods to send request to server. The bellow mentioned methods are some of them

abort()
open(method, URL)
open(method, URL, async)
send(content)

In ASP.net 2.0 a new feature is added to handle the partial handling of the postback it is known as ClientCallback.

To implement Client Callback -the server side code must have to:



Implement ICallbackEventHandler interface.
Need to have an implementation of GetCallbackResult()
Needs to have an implementation of RaiseCallbackEvent()


To implement Client Callback -the client side code must have three functions which implement the following features:



A method which acts as a helper method to send requests to the server which would be created automatically by GetCallbackEventReference method.
A method which acts as a helper method to receive the response from the server.
A method which acts as helper method which send the request.


Steps



Implement ICallbackEventHandler interface.


Partial Class CallBack
Inherits System.Web.UI.Page
Implements ICallbackEventHandler




Implementation of GetCallbackResult()


Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackRes ult
Return sResult
End Function

Returns: A string that represents an event argument to pass to the event handler



Implementation of RaiseCallbackEvent()


Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackE vent

End Sub



Configure the client side handling of the Callback from the server side

Create a reference of ClientScriptManager
Create a reference to the client side function which would be handling the CallBack using GetCallbackEventReference method. It takes the following argument.



A reference to the page
Name of the argument through which you pass the data
Name of the function which receives the Callback
An argument that passes any specific data


Use RegisterStartupScript method to attach the function into the page.

Dim oCM As ClientScriptManager = Page.ClientScript
Dim sCBRef As String = oCM.GetCallbackEventReference(Me, "arg", "GetResponse", "")
Dim sCallBackScript As String = "function PostRequest(arg,context) {" & sCBRef & ";}"
oCM.RegisterStartupScript(Me.GetType, "PostRequest", sCallBackScript, True)



On the client side call the PostRequest [method name given the Server side code] method with the arguments and the context if any.


function SendArg()
{
var xddlArg1 = document.getElementById("xddlArg1");
var iArg1 = xddlArg1.options[xddlArg1.selectedIndex].text;
var xddlArg2 = document.getElementById("xddlArg2");
var iArg2 = xddlArg2.options[xddlArg2.selectedIndex].text;

PostRequest(iArg1+","+iArg2,"")

}


Use the GetResponse [method name given the Server side code] to get the response from the server.


function GetResponse(i_iResult)
{
document.getElementById('xtxtResult').value=i_iRes ult;
}


The following markup shows a sample event which could be used for invoking the Callback.

<input type="button" id="xbtnMul" onclick ="SendArg()" value="=" />

The trivial part is you are already using these in you datagrid applications, if you are using the EnableSortingAndPageCallbacks property. They call the RenderControl method by itself and send back the response to the client.

Conclusion

This article has shown uses of ASP.NET 2.0's Client Callback feature. We have seen how a simple page can call a server-side method. I am not saying that ASP.NET AJAX is bad; you can call Web Services from cross browser environment, you have complex controls which can be implemented with ease. But when your needs are limited, ICallbackEventHandler can do the job for you. Do you know this is used everywhere in SharePoint?



Download Sample Code (http://bdotnet.in/blogs/nareshkumarhk/CallBack.zip) Happy Coding :)




http://bdotnet.in/blogs/nareshkumarhk/archive/2008/08/12/how-to-implement-client-callback-in-asp-net-without-using-asp-net-ajax.aspx








Client-Callback Implementation (C#) Example

Demonstrates an ASP.NET Web page that implements a client callback. For more information, see Implementing Client Callbacks Without Postbacks in ASP.NET Web Pages (http://msdn.microsoft.com/en-us/library/ms178208%28VS.80%29.aspx).
Example

The following code example is in two parts. The first part of the example shows an ASP.NET Web page (the .aspx page). The second part shows the corresponding code-behind file (the .aspx.cs file).

C#
Copy Code (javascript:CopyCode('ctl00_MTContentSelector1_mai nContentContainer_ctl02CSharp');)

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html >
<head id="Head1" runat="server">
<title>Client Callback Example</title>
<script type="text/ecmascript">
function LookUpStock()
{
var lb = document.getElementById("ListBox1");
var product = lb.options[lb.selectedIndex].text;
CallServer(product, "");
}

function ReceiveServerData(rValue)
{
document.getElementById("ResultsSpan").innerHTML = rValue;

}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" Runat="server"></asp:ListBox>
<br />
<br />
<button type="Button" onclick="LookUpStock()">Look Up Stock</button>
<br />
<br />
Items in stock: <span id="ResultsSpan" runat="server"></span>
<br />
</div>
</form>
</body>
</html>


C#
Copy Code (javascript:CopyCode('ctl00_MTContentSelector1_mai nContentContainer_ctl03CSharp');)

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 ClientCallback : System.Web.UI.Page,
System.Web.UI.ICallbackEventHandler
{
protected System.Collections.Specialized.ListDictionary catalog;
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
String cbReference =
Page.ClientScript.GetCallbackEventReference(this,
"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.G etType(),
"CallServer", callbackScript, true);

catalog = new System.Collections.Specialized.ListDictionary();
catalog.Add("monitor", 12);
catalog.Add("laptop", 10);
catalog.Add("keyboard", 23);
catalog.Add("mouse", 17);

ListBox1.DataSource = catalog;
ListBox1.DataTextField = "key";
ListBox1.DataBind();

}

public void RaiseCallbackEvent(String eventArgument)
{
if (catalog[eventArgument] == null)
{
returnValue = "-1";
}
else
{
returnValue = catalog[eventArgument].ToString();
}
}
public String GetCallbackResult()
{
return returnValue;
}





}



The Web page emulates a database lookup to determine the number of items that are available, or in stock, for a series of products (monitors, keyboards, and so on). To simplify this code example, the database is represented by a dictionary list that contains a small set of items. For each item in the table, the key is the item name (such as monitor) and the value is the number of items that are in stock. In a production application, a database would be used instead.
When the page runs, a ListBox (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listbox%28VS.80%29.aspx) control is bound to the hash table so that the ListBox control displays the list of products. The page also contains a button element (not a Button Web server control), whose onclick event is bound to a client function named LookUpStock. When users click the button, the button executes the LookUpStock function, which gets the current selection from the list box and then performs the client callback by calling the CallServer function.
The code-behind page adds client-side script to the page via the RegisterClientScriptBlock (http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerclientsc riptblock%28VS.80%29.aspx) method. The script that is added to the page includes a function called CallServer, which gets the name of the method that will post back to the server from the GetCallbackEventReference (http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.getcallbackevent reference%28VS.80%29.aspx) method.
The client callback invokes the RaiseCallbackEvent (http://msdn.microsoft.com/en-us/library/system.web.ui.icallbackeventhandler.raisecallbacke vent%28VS.80%29.aspx) method, to determine the available stock for the product passed to it. The GetCallbackResult (http://msdn.microsoft.com/en-us/library/system.web.ui.icallbackeventhandler.getcallbackres ult%28VS.80%29.aspx) method returns the value. Note that the arguments sent between the client script and the server code can only be strings. To pass in or to receive multiple values, you can concatenate values in the input or return string, respectively.
http://www.atyafonline.com/vb/imgcache/1721.pngSecurity Note When you use this feature, there are potential security threats. Callback arguments are not validated and therefore should be considered unsafe. You should always check the contents of the arguments before using them. For details, see Script Exploits Overview (http://msdn.microsoft.com/en-us/library/w1sw53ds%28VS.80%29.aspx).



See Also

Tasks

How to: Implement Callbacks in ASP.NET Web Pages (http://msdn.microsoft.com/en-us/library/ms366518%28VS.80%29.aspx)
Concepts

Implementing Client Callbacks Without Postbacks in ASP.NET Web Pages (http://msdn.microsoft.com/en-us/library/ms178208%28VS.80%29.aspx)
Client Callback with Validation Implementation Example (http://msdn.microsoft.com/en-us/library/ms366515%28VS.80%29.aspx)





http://msdn.microsoft.com/en-us/library/ms178210(VS.80).aspx (http://msdn.microsoft.com/en-us/library/ms178210%28VS.80%29.aspx)