AJAX and User Controls


AJAX (Asynchronous JavaScript and XML) enables you to update content in a page without posting the page back to the server. Behind the scenes, AJAX uses the XMLHttp ActiveX component (in the case of Microsoft Internet Explorer) or the XMLHttpRequest intrinsic browser object (in the case of other browsers such as FireFox).

In the ASP.NET Framework, AJAX is referred to as client callbacks. To add AJAX support to a User control, you must implement the ICallBackEventHandler interface and add the necessary JavaScript scripts to process the results of the AJAX call.

Here are the steps for implementing AJAX:

1.

Create a client script for invoking the AJAX call. You can get this script with the Page.ClientScript.GetCallbackEventReference() method.

2.

Create server methods named RaiseCallbackEvent() and GetCallbackResult(), which returns a string value from the server.

3.

Create a client method that receives the value from the server RaiseCallbackEvent() method and does something with the value.

For example, the User control in Listing 7.12 randomly displays one of three quotations. The quotation is updated automatically every 10 seconds (see Figure 7.4).

Figure 7.4. Using AJAX to display a random quotation.


Listing 7.12. RandomQuotation.ascx

[View full width]

<%@ Control Language="VB" ClassName="RandomQuotation" %> <%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %> <%@ Import Namespace="System.Collections.Generic" %> <script runat="server">     Public Sub RaiseCallbackEvent(ByVal result As String) Implements ICallbackEventHandler .RaiseCallbackEvent     End Sub     Public Function GetCallbackResult() As String Implements ICallbackEventHandler .GetCallbackResult         Dim quotes As New List(Of String)()         quotes.Add("All paid jobs absorb and degrade the mind -- Aristotle")         quotes.Add("No evil can happen to a good man, either in life or after death -- Plato")         quotes.Add("The only good is knowledge and the only evil is ignorance -- Plato")         Dim rnd As Random = New Random()         Return quotes(rnd.Next(quotes.Count))     End Function     Private Sub Page_Load()         Dim callback As String = Page.ClientScript.GetCallbackEventReference(Me, Nothing,  "UpdateQuote", Nothing, "CallbackError", True)         Dim startupScript As String = String.Format("setInterval( ""{0}"", 5000 )", callback)         Page.ClientScript.RegisterStartupScript(Me.GetType(), "RandomQuotation",  startupScript, True)     End Sub </script> <div  > Random Quotation </div> <script type="text/javascript">     function UpdateQuote(result)     {         var divQuote = document.getElementById('divQuote');         divQuote.innerText = result;     }     function CallbackError(result)     {         alert( result );     }  </script>

The Page_Load() method in Listing 7.12 generates the client script for invoking the AJAX call. A reference to the script that makes the AJAX call is retrieved from the Page.ClientScript.GetCallbackEventReference() method. The JavaScript setInterval() method is used to execute this script every five seconds.

The User control implements the ICallbackEventHandler interface. This interface has two methods that you must implement: RaiseCallbackEvent() and GetCallbackResult(). These two methods are called on the server in order. In Listing 7.12, the RaiseCallbackEvent() does nothing and the GetCallbackResult() method returns the random quotation to the client.

Finally, notice that the User control contains a client script block that contains two JavaScript functions. The first function, named UpdateQuote(), displays the random quotation returned by the RaiseCallbackEvent() in an HTML <div> tag. The second method, named CallbackError(), shows an alert dialog box when an error occurs during performance of the AJAX call.

The page in Listing 7.13 illustrates how you can use the RandomQuotation User control. It contains the User control and it also displays the current time.

Listing 7.13. ShowRandomQuotation.aspx

<%@ Page Language="VB" %> <%@ Register TagPrefix="user" TagName="RandomQuotation"     src="/books/3/444/1/html/2/~/RandomQuotation.ascx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <style type="text/css">         .quote         {             width:200px;             padding:20px;             border:Dotted 2px orange;             background-color:#eeeeee;             font:16px Georgia,Serif;         }     </style>     <title>Show Random Quotation</title> </head> <body>     <form  runat="server">     <div>     <%= DateTime.Now %>     <br />     <user:RandomQuotation                  Runat="server" />     </div>     </form> </body> </html>

Notice that the random quotation is updated, but that the time on the page does not change. Only the area of the page that contains the random quotation is updated.




ASP. NET 2.0 Unleashed
ASP.NET 2.0 Unleashed
ISBN: 0672328232
EAN: 2147483647
Year: 2006
Pages: 276

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net