ASP.NET V2.0 Client-Side JavaScript Callbacks (AJAX)
ASP.NET 2.0 lets you retrieve page values and populate them to an already
generated web page without re-rendering the entire page. Thus, you can update
portions of a web page without going through the entire postback cycle. This
increases the page's performance and enhances the user's experience. To
understand this better, I suggest you read my AJAX
tutorial, since the functionality here really wraps functionality based
on IE's XmlHTTP object or the XmlHTTPRequest
object used by other browsers.
In a normal wep page postback situation, some event, a button click maybe,
triggers an HTTP Post request to be sent to the web server. The web
server processes the event with the IPostbackEventHandler
and runs the event through several page events including loading the page state
as found in viewstate, processing data, processing postback events, and
rendering the page to the browser. This completely reloads the page causing the
browser to flicker.
With a client-side callback, something, like a button click, triggers an event
to be posted to a script event handler , which is
a client-side JavaScript function, that sends an asynchronous
request to the web server. Because it is an asynchronous out-of-ban call, the
user can still view, scroll, and work with the web page.
On the server, the ICallbackEventHandler runs the
event through similar processing as above but the big steps, like rendering the
page, are skipped. The results, a much smaller amount of data, are sent back to
the client's script callback object. Javascript on the client then refreshes
only the appropriate parts of the page, faster, and without the flicker.
Sample Client-Side HTML and JavaScript Code:
<html>
<head runat="server">
<title>AJAX Sample</title>
<script type="text/javascript">
function GetNumber()
{
UseCallback();
}
function HandleEvent(TextBox1, context)
{
document.forms[0].TextBox1.value = TextBox1;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Increment Number" onclick="GetNumber()" />
<br /><br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
The sample page contains an HTML button and a TextBox server control. A standard
HTML button is used because an <asp:button> control won't work. The
button has an onClick event which triggers the GetNumber() Javascript
function.
The GetNumber() Javascript function calls the client script handler, UseCallback(),
that is defined in the page's code behind. A string result from GetNumber() is
retrieved using the HandleEvent() client-side function which populates the
textbox with the result.
Sample Server-Side Code:
public partial class Page1 : System.Web.UI.Page,
System.Web.UI.ICallbackEventHandler
{
private string _callbackResult = null;
protected void Page_Load(object sender, EventArgs e)
{
//
// Get a reference to a client function that, when invoked, initiates
// a client-call back to a server event.
// Arguments:
// - this - Server control that handles the callback. It must implement the
// ICallbackEventHandler interface and provide a RaiseCallbackEvent
// method.
// - arg - Argument passed from the client to the server.
// - HandleEvent - Name of the client-side event handler that receives the
// results of the server side event.
// - context - Client-side script that is evaluated on the client prior to
// initiating the callback.
//
string callbackReference = Page.ClientScript.GetCallbackEventReference(
this, "arg", "HandleEvent", "context");
string callbackScript =
"function UseCallback(arg, context) {" + callbackReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(
this.GetType(), "UseCallback", callbackScript, true);
}
public void RaiseCallbackEvent(string eventArg)
{
Random rnd = new Random();
_callbackResult = rnd.Next().ToString();
}
public string GetCallbackResult()
{
return _callbackResult;
}
}
The page implements the System.Web.UI.ICallbackEventHandler
interface which requires that you implement the RaiseCallbackEvent
and GetCallbackResult methods, which both work
with the client script request.
The RaiseCallbackEvent method lets you retrieve the
value from the web page, but it must be of type string. It is in this event
that you add whatever logic is necessary to perform the desired task, return a
random number, in our case.
The GetCallbackResult method is the method that
actually passes the server-side result back to the client. Again, as a
string.
The Page_Load event uses the Page.ClientScript.RegisterClientScriptBlock
method to create the client callback script manager, UseCallback() in
our example, on the client.
Passing Values from the Client-Side Code to the Server-Side Code:
The above code can modified to pass an argument from the client-side code to the
server-side code. In the client JavaScript, we can get the value the user types
into the textbox and pass that to the server. Note the new parameter added to
the UseCallback() function.
<script type="text/javascript">
function GetNumber()
{
var num = document.forms[0].TextBox1.value;
UseCallback(num);
}
function HandleEvent(TextBox1, context)
{
document.forms[0].TextBox1.value = TextBox1;
}
</script>
A slight change is needed to the server code. We can get the value using the eventArg
parameter:
public void RaiseCallbackEvent(string eventArg)
{
Random rnd = new Random();
rnd = rnd.Next() + parserInt(eventArg)
_callbackResult = rnd.ToString();
}
}
While this is a very simplistic example, it illustrates the concept of making
out-of-band AJAX calls.
As mentioned at the start of this page, the capabilities here rely on
XmlHTTP. Therefore the client browser must support XmlHTTP for this
to work. You can check this using the Page.Request.Browser.SupportsXmlHttp
property in the Page_Load event in the code behind.
To see how to use JavaScript to update parts of a web page asynchronously
without posting back and refreshing the entire page in ASP.NET 1.1, see my
AJAX Tutorial.
|