Documente Academic
Documente Profesional
Documente Cultură
NET
Pgina 1 de 8
his article will show you how AJAX can be used on ASP.NET web pages by means of the increasingly popular JQuery (JavaScript) library. It will explain how to use jQuery for this, and what the advantages are of using it.
In the last few years, we have seen an increasing interaction between the user and the web sites as a result of the design and technology ideas that we refer to as Web 2.0. Today Web 2.0 sites host, and manage, a lot of data about their users. Web users store their data (images, video and so on) online, update it on a regular basis, share it with other users, post comments on blogs and so on. This trend has, in turn, lead to an increase in the number of round trips between clients and servers. In the traditional Web model, users ask for a static page, the server gets it back to them and the browser then renders the page in its entirety. Then the users move on to the next page. On a data-intensive site, this extra activity will not only increase the network traffic, but will also force the user to wait for the page to be rendered every time any data is changed. Today, users of a Web 2.0 site will be able to request information, or make changes, and will get the information they need when parts of the pages content is refreshed from data supplied by the server without them having to move to another page. The key technology for solving this problem is AJAX, a technique that allows JavaScript to make an HTTP POST or GET request to fetch, or send , data; whilst not requiring a complete refresh of the page.
So what is AJAX?
AJAX, according to Jesse Garrett who coined the term, is an acronym (Asynchronous Javascript And XML) that combines several long-standing technologies together.
l l l l l
Using the browsers XMLHttpRequest object to transfer data asynchronously between the client and server. Using XML( or JSON) as the format for the data being transferred. Using XHTML and CSS for structure and presentation. Using the Document Object Model to render information within the browser page. Using Javascript to bind everything together.
The client browser uses JavaScript functions to perform a call to the server and the server responds to it asynchronously. This means that, after the client request, JavaScript in the web page continues to execute whilst it waits for a response from the server. The overall process is made possible by using the XmlHttpRequest object. It was introduced by Microsoft as an ActiveX component starting from Internet Explorer 5.0. Today, all browsers have their own implementation of it. In the traditional Browser approach to returning requested information to the user: 1. 2. 3. The browser requests a page (using GET or POST method) from the web server using the URL of the page. If the page exists, the server responds to the browser by sending to it the requested HTML page. The browser gets the page content and renders it on its surface.
http://www.simple-talk.com/content/print.aspx?article=1031
18/01/2011
Pgina 2 de 8
3.
Some JavaScript code on the client begins an HTTP request to the web server by using the XmlHttpRequest object and continues with its execution. After the server has serviced the request, it passes the result back to the browser. This invokes a JavaScript function (the callback) within the client by passing to it, as arguments, the result of the execution as XML document. The callback function parses the data and updates the pages content.
Microsoft ASP.NET technology integrated AJAX technology by introducing the AJAX Extension to the .NET Framework. This is based on some server controls (the principal one is the UpdatePanel control), that allows you to add AJAX capabilities to ASP.NET web forms. However, several other solutions are available that provide a more general solution to implementing AJAX across different server platforms.
AJAX libraries
As developer, you will probably only rarely need to work directly with the XmlHttpRequest object; this is because developers generally now make use of JavaScript libraries to implement JavaScript functionality on their web pages. There are many free powerful JavaScript libraries today available on the web. To name a few of them: JQuery, ExtJS, prototype, script.acoul.us, Dojo, Yahoo! UI library, Google Web Toolkit. These libraries make Ajax easier to use by hiding the hard work that is required when working with JavaScript. If you find that you really need to access the XmlHttpRequest object directly, you will find a good guide on the Apple Developer Center on how to use it. The use of a JavaScript library speeds up development work; even Microsoft AJAX Extensions are based on a JavaScript library. This is the Microsoft Ajax Library. The scripts files are embedded as resources on the System.Web.Extensions assembly and they are responsible to manage all the task needed to perform partial rendering with UpdatePanels . For this article, well be showing you how to use the JQuery library in preference to Microsoft AJAX Extensions.
<?xml version="1.0" encoding="utf-8" ?> <sentences> <sentence id="0"> Certainly there are things in life that money can't buy, but it's very funny - Did you ever try buying then without money?</sentence> <sentence id="1"> Progress might have been alright once, but it has gone on too long. </sentence> <sentence id="2"> The most exciting happiness is the happiness generated by forces beyond your control.</sentence> </sentences>
To use our data source, we need a simple method that will open the xml file and will extract a specific sentence. For simplicity, well decide that the sentence will be randomly selected. To do so, we put on the code behind of our default.aspx page the following method:
private string GetSentence() { int index = new Random().Next(3); XDocument doc = XDocument.Load(Server.MapPath("/sentences.xml"));
http://www.simple-talk.com/content/print.aspx?article=1031
18/01/2011
Pgina 3 de 8
The previous method extracts a random number between 0 and 2 by using the Random class. The number extracted is then used on the LINQ query to get the text of the randomly selected sentence. This is finally returned to the caller as simple text.
<asp:ScriptManager ID="scriptManager" runat="server" EnableCdn="True" AjaxFrameworkMode="Disabled" > <Scripts> <asp:ScriptReference Paththth="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.1.min.js" /> </Scripts> </asp:ScriptManager>
If you inspect the previous block of code, you will see that, to allow the utilization of the CDN, the ScriptManager on .NET Framework 4.0 implements the new EnableCdn property that must be set to true. Traditionally, the ScriptManager was developed with the intent to provide JavaScript registration on the page when working with UpdatePanels (and with Microsoft AJAX Extensions in general). Its main purpose was to register the required Microsoft Ajax Librarys JavaScript files on the client, getting their content from the System.Web.Extension assemblys resources. As we see on the previous block of code, the new ScriptManager allows you the option to disable the Microsoft Ajax Librarys scripts registration by setting to Disabled the new property AjaxFrameworkMode. So, starting from .NET Framework 4.0, ScriptManager seems to be becoming the standard way to manage all the JavaScript code needed by our pages. In this case, we have used it to register, on the client, the JQuery library from the CDN.
<asp:ScriptManager ID="scriptManager" runat="server" EnableCdn="True" AjaxFrameworkMode="Disabled" > <Scripts> <asp:ScriptReference Paththth="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.1-vsdoc.js" /> </Scripts> </asp:ScriptManager>
Remember to revert the vsdoc with the .min suffix when your site will be released. This will increase the site speed by reducing the quantity of JavaScript code that the client had to download. If the .min version is a JavaScript file that occupies 69 KB on disk, the vsdoc version has length given by 229 KB.
http://www.simple-talk.com/content/print.aspx?article=1031
18/01/2011
Pgina 4 de 8
The getSentence JavaScript function must contain the code needed to get a sentence form the server, using JQuery. For this to happen, we use the .ajax() method of the main JQuery object $. This method accepts, as input, a JavaScript object that has all the elements that are needed to perform an AJAX call to the server. We dont need all of them and so well only describe here the most commonly used. For a full list, see the JQuery documentation at jQuery.ajax (settings) url: JQuery will use the XmlHttpRequest object to perform a request to the server at this url. It will use the GET method, unless a different value for the type element is specified. data: Data can be sent to the server, either as query string attached to the url of the GET request, or in a POST request . Data must be expressed as JSON formatted object. Data can be also be sent to the server by directly adding the query string to the url element. success: This allows us to set the callback function that must be executed on the client after the server response is received successfully. It is used to refresh the pages content. When called, the parameters that are passed as arguments are: (1) data, that represent the data received by the server, (2) textStatus, that is a string describing the status of the response and (3) XmlHttpRequest that represents the instance of the XmlHttpRequest object used for the request. dataType: This specifies the type of data expected by the client. It can be html, text, xml, script, json and jsonp. If nothing is specified, the method will try to interpret data received on the basis of the content type of the response. While html, text, and xml are obvious, the other types need explaining. if we use the script value, the method will expect some JavaScript code, if we use json (or the less known jsonp) value, then the method will try to convert the response into a JavaScript object. error: This allows you to set a JavaScript callback function that will be invoked if some error occurs during the AJAX request. Its arguments are: (1) XmlHttpRequest, that represents the instance of the XmlHttpRequest object used for the request, (2) textStatus, that is a string describing the status of the response, (3) errorThrown that is a string that represent the description of the error generated. complete:If this is set, than the JavaScript function that youve specified will be invoked at the end of the process, after that the success or error function are executed. Its arguments are: (1) XmlHttpRequest that represents the instance of the XmlHttpRequest object used for the request, (2) textStatus, that is a string describing the status of the response. Our getSentence() function will then look like this:
<script type="text/javascript"> function getSentence() { $.ajax( { url: "default.aspx", data: "get=sentence", success: function (data) { $("#txtSentence").get(0).value = data; }, error: function () { alert(arguments[2]); }
http://www.simple-talk.com/content/print.aspx?article=1031
18/01/2011
Pgina 5 de 8
}); } </script>
We have defined the callback function as an anonymous JavaScript function object and we have set the success element to its value. After the server response, this function will be invoked and its content will be executed. The functions body shows what will happen. By using the JQuery function $, using as the selector the id of the TextBox, its value will be changed to the value of the returned data. If an exception occurs, the error function will be invoked, and the exceptions description will be shown on the screen. We get the error description from the third argument passed to the JavaScript function. So, it will be contained on the arguments[2] array item. Youll notice that we decided to specify a value for the data element. This value will be sent to the server as a query string. This is because our design requires that we need a trick to signal, on the server side, that the request is an AJAX request rather than a normal GET request. Remember that AJAX requests are made by invoking a server resource by using either the GET or POST method of the HTTP protocol. So If we use the GET, the ASP.NET pages are not able to distinguish an AJAX request form a standard GET request. We intercept the AJAX request by checking the query string of the same. If the request contains the key get on its query string, an AJAX request was made, if it doesnt, the page will respond as for normal GETs. So, on the OnLoad event of our web page we could write something like this:
protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (Request.QueryString["get"] != null) { Response.Clear(); Response.ContentType = "text/plain"; Response.Write(GetSentence()); Response.End(); } }
If the query string contains a key named get, we know that the client is asynchronously waiting for a sentence as plain text. In this case: we (1) clear the response buffer, (2) set the content type to text/plain (so that JQuery will know how to interpret it), (3) write to the response stream the string selected with the GetSentence() method, (4) end the response. After that, the callback function will be invoked on the client, passing the string as the value for the data argument. As we have specified, the TextBox will be filled with the extracted value. You can download a copy of this example at the top of the article in the file "SupportingDocuments".
http://www.simple-talk.com/content/print.aspx?article=1031
18/01/2011
Pgina 6 de 8
private string GetSentence() { int index = new Random().Next(3); XDocument doc = XDocument.Load(Server.MapPath("/sentences.xml")); var q = from s in doc.Descendants("sentence") where (int)s.FirstAttribute == index select s; StringBuilder sb = new StringBuilder(); sb.Append("{\"id\":\""); sb.Append(q.First<XElement>().Attribute("id").Value); sb.Append("\", \"sentence\":\""); sb.Append(q.First<XElement>().Value); sb.Append("\"}"); return sb.ToString(); }
This new method selects a sentence and then creates a JSON string that contains the id of the sentence in addition to the sentences text. The returned string will be something like this:
{id:<extracted_id>,sentence: <extracted_sentence>}
Where the <extracted_id> and the <extracted_sentence> are the id and the text of the selected sentence. The OnLoad method of the page must be modified as follows:
protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (Request.QueryString["get"] != null) { Response.Clear(); Response.ContentType = "application/json"; Response.Write(GetSentence()); Response.End(); } }
We have modified the content type of the response from text/plain to application/json. Finally, we change the JavaScript callback on the client in this way:
<script type="text/javascript"> function getSentence() { $.ajax( { url: "default.aspx", data: "get=sentenct", success: function (data) { $("#txtID").get(0).value = data.id; $("#txtSentence").get(0).value = data.sentence; }, error: function () { alert(arguments[2]); } }); } </script>
The JQuery .ajax() method automatically transforms the JSON string into a JavaScript object , on the basis of the content type of the response, and passes it to the success function. The created JavaScript object will have two properties: the .id properties with the id of the sentence and the .sentence property with the text of the same. This structure reflects the original JSON string structure. We use the two properties to update our page.
http://www.simple-talk.com/content/print.aspx?article=1031
18/01/2011
Pgina 7 de 8
If you run the application, the two TextBoxes will be hidden after the button-click by reducing the div tag height to 0 with a speed given by the JQuery-defined value normal. After the selection of the new sentence, the two TextBoxes will reappear on the page by resetting the height of the div tag to its original value with a speed identical to the previous. You can download a copy of this example at the top of the article in the file "SupportingDocuments".
Conclusion
In this article weve use JQuery to implement AJAX features on a web page. We have seen how easy it is to perform common AJAX tasks in JQuery (and in general JavaScript libraries that supports AJAX capabilities), because it is easier to modify those AJAX requests without being limited to perform only a partial rendering of the page. Partial rendering allow us only to update server controls contained on some UpdatePanel. The update occurs when we change some properties of those controls on the server side. With AJAX libraries we are free to select any kind of data source we want. We need only to serialize them, maybe using JSON, and send them to the client. However, this doesnt mean that ASP.NET UpdatePanels should not be used anymore. They are very easy to use and very quick to setup. With a simple drag and drop in Visual Studio, we have all the machinery to perform AJAX
http://www.simple-talk.com/content/print.aspx?article=1031
18/01/2011
Pgina 8 de 8
requests without having to write any other blocks of code. And this is the purpose of server controls: To make our life easier. When a server control can do it, allow it to do it, otherwise look elsewhere. And if youre looking for more configurable AJAX work, then jQuery is a good library to consider.
Simple-Talk.com
http://www.simple-talk.com/content/print.aspx?article=1031
18/01/2011