{"id":885,"date":"2010-05-19T00:00:00","date_gmt":"2010-05-19T00:00:00","guid":{"rendered":"https:\/\/test.simple-talk.com\/uncategorized\/ajax-basics-with-jquery-in-asp-net\/"},"modified":"2021-05-17T18:35:03","modified_gmt":"2021-05-17T18:35:03","slug":"ajax-basics-with-jquery-in-asp-net","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/ajax-basics-with-jquery-in-asp-net\/","title":{"rendered":"AJAX basics with jQuery in ASP.NET"},"content":{"rendered":"<div id=\"pretty\">\n<h1>A Step Ahead of the UpdatePanel<\/h1>\n<p class=\"start\">This 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.<\/p>\n<p>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 \u00a0Web 2.0.<\/p>\n<p>Today Web 2.0 sites host, and manage, a lot of \u00a0data 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.<\/p>\n<p>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. \u00a0On 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.<\/p>\n<p>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 page&#8217;s content is refreshed from data \u00a0supplied by the server without them having to move to another page.<\/p>\n<p>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.<\/p>\n<h1>So what is AJAX?<\/h1>\n<p>AJAX, according to Jesse Garrett who coined the term, is an acronym (Asynchronous Javascript And XML)\u00a0 that combines several long-standing technologies together.<\/p>\n<ul>\n<li>Using the browser&#8217;s <b>XMLHttpRequest<\/b> object to transfer data asynchronously between the client and server.<\/li>\n<li>Using XML( or JSON) as the format for the data being transferred.<\/li>\n<li>Using XHTML and CSS for structure and presentation.<\/li>\n<li>Using the Document Object Model\u00a0 to render information within the browser page.<\/li>\n<li>Using Javascript to bind everything together.<\/li>\n<\/ul>\n<p>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.<\/p>\n<p>The overall process is made possible by using the XmlHttpRequest object. It was introduced by\u00a0 Microsoft as an ActiveX component starting from Internet Explorer 5.0. \u00a0Today, all browsers have their own implementation of it.<\/p>\n<p>In the traditional Browser approach to returning requested information to the user:<\/p>\n<ol>\n<li>The browser requests a page (using GET or POST method) from \u00a0the web server using the URL of the page.<\/li>\n<li>If the page exists, the server responds to the browser by sending to it the requested HTML page.<\/li>\n<li>The browser gets the page content and renders\u00a0 it on its surface.<\/li>\n<\/ol>\n<p>AJAX works in a quite different way.<\/p>\n<ol>\n<li>Some JavaScript code on the client begins an HTTP request to the web server by using the XmlHttpRequest object and continues with its execution.<\/li>\n<li>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.<\/li>\n<li>The callback function parses the \u00a0data and updates the page&#8217;s content.<\/li>\n<\/ol>\n<p>Microsoft ASP.NET technology integrated AJAX technology by introducing the AJAX\u00a0 Extension to the .NET Framework. This is based on some server controls (the principal one is the <b>UpdatePanel<\/b> 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.<\/p>\n<h1>AJAX libraries<\/h1>\n<p>As developer, you will probably only rarely need to work directly with the <b>XmlHttpRequest<\/b> 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.<\/p>\n<p>These \u00a0libraries make Ajax easier to use by &#8220;hiding&#8221; the hard work that is required when working with JavaScript. \u00a0If you find that you really need to access the <b>XmlHttpRequest<\/b> object directly, you will find a good guide on the Apple Developer Center on how to use it.<\/p>\n<p>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 <b>System.Web.Extensions<\/b> assembly and they are responsible to manage all the task needed to perform partial rendering with <b>UpdatePanels<\/b> .<\/p>\n<p>For this article, we&#8217;ll be showing you how to use the JQuery library in preference to Microsoft AJAX Extensions.<\/p>\n<h2>Preparing The Server Side Code<\/h2>\n<p>We&#8217;ll start our work with a simple example. For it, we need to set up a data source that will be queried by the client in order to update the content of the client&#8217;s page.<\/p>\n<p>We can implement a simple default.aspx web page that gets a sentence from the server when the user clicks a button. Although we&#8217;d need to show data provided by web services or WCF services (and in general RESTful services) to demonstrate the true potential of AJAX , we&#8217;ll start with a very simple example using, as our data source, \u00a0an XML document (sentences.xml) with this content:<\/p>\n<pre class=\"lang:c# theme:vs2012\">&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;  \r\n&lt;sentences&gt;  \r\n\u00a0 &lt;sentence id=\"0\"&gt; Certainly there are things in life that money can't buy, but it's very funny - Did you ever try buying then without money?&lt;\/sentence&gt;  \r\n\u00a0 &lt;sentence id=\"1\"&gt; Progress might have been alright once, but it has gone on too long. &lt;\/sentence&gt;  \r\n\u00a0 &lt;sentence id=\"2\"&gt; The most exciting happiness is the happiness generated by forces beyond your control.&lt;\/sentence&gt;  \r\n&lt;\/sentences&gt;  \r\n<\/pre>\n<p>To use our data source, we need a simple method that will open the xml file and will extract a specific sentence. For simplicity, we&#8217;ll decide \u00a0that the sentence will be randomly selected. To do so, we put on the code behind of our default.aspx page the following method:<\/p>\n<pre class=\"lang:c# theme:vs2012\">private string GetSentence()\r\n{\r\n\u00a0\u00a0\u00a0 int index = new Random().Next(3);\r\n\u00a0\r\n\u00a0\u00a0\u00a0 XDocument doc =\r\n\u00a0\u00a0\u00a0\u00a0 XDocument.Load(Server.MapPath(\"\/sentences.xml\"));\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 var q = from s in doc.Descendants(\"sentence\")\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 where (int)s.FirstAttribute ==\u00a0 index select s;\r\n\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return q.First&lt;XElement&gt;().Value;\r\n}\r\n<\/pre>\n<p>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.<\/p>\n<h2>The Microsoft Ajax\u00a0 Content Delivery Network (CDN)<\/h2>\n<p>To complete the server side code, we need to allow our ASP.NET page to use the JQuery library. We could just download the JQuery script file from the JQuery site and put it on our solution. There is a better approach. \u00a0We can use the Microsoft Ajax Content Delivery Network. The improved support of the new .NET Framework 4.0 for JavaScript libraries has even been extended to the task of downloading \u00a0JavaScript files by the client. To increase the page&#8217;s Load performance, Microsoft created a new service, called the Microsoft Ajax Content Delivery Network (CDN) that hosts a range of common resources needed by a web page on &#8220;edge cache&#8221; servers, thereby improving the page&#8217;s load-time. You can read more about the CDN on the Scott Guthrie&#8217;s blog at <a href=\"http:\/\/weblogs.asp.net\/scottgu\/archive\/2009\/09\/15\/announcing-the-microsoft-ajax-cdn.aspx\">Announcing the Microsoft AJAX CDN<\/a><b> <\/b><\/p>\n<p>We choose the second options. We use a <b>ScriptManager<\/b> to register the JQuery library to our web page using, as source, the CDN as follow:<\/p>\n<pre class=\"lang:xhtml theme:github\">&lt;asp:ScriptManager ID=\"scriptManager\" runat=\"server\"  \r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 EnableCdn=\"True\" AjaxFrameworkMode=\"Disabled\" &gt;\r\n\u00a0\u00a0 &lt;Scripts&gt;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 &lt;asp:ScriptReference \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Paththth=\"http:\/\/ajax.microsoft.com\/ajax\/jquery\/jquery-1.4.1.min.js\" \/&gt;\r\n\u00a0 \u00a0&lt;\/Scripts&gt;\r\n&lt;\/asp:ScriptManager&gt;\r\n<\/pre>\n<p>If you inspect the previous block of code, you will see that, to allow the utilization of the CDN, the <b>ScriptManager<\/b> on .NET Framework 4.0 implements the new <b>EnableCdn <\/b>property that must be set to true.<\/p>\n<p>Traditionally, the <b>ScriptManager<\/b> was developed with the intent to provide JavaScript registration on the page when working with <b>UpdatePanels<\/b> (and with Microsoft AJAX Extensions in general). Its main purpose was to register the required\u00a0 Microsoft Ajax Library&#8217;s JavaScript files on the client, getting their content from the <b>System.Web.Extension <\/b>assembly&#8217;s resources. As we see on the previous block of code, the new <b>ScriptManager<\/b>\u00a0 allows you the option to disable the Microsoft Ajax Library&#8217;s scripts registration by setting to <b>Disabled<\/b> the new property <b>AjaxFrameworkMode<\/b>.\u00a0 So, starting from .NET Framework 4.0, <b>ScriptManager<\/b> 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.<\/p>\n<h1>Getting jQuery intellisense.<\/h1>\n<p>Visual Studio 2010 support for JQuery \u00a0extends to providing\u00a0 intellisense \u00a0when working with this library.\u00a0 Visual Studio 2010 is able to use the comments contained on a special version of the JQuery library in order to populate the intellisense window as for the standard .NET classes. To use this feature, all you need to do is to replace the .min suffix with the <b>-vsdoc<\/b> suffix on the <b>ScriptReference<\/b> declaration of the <b>ScriptManager<\/b>:<\/p>\n<pre class=\"lang:xhtml theme:github\">&lt;asp:ScriptManager ID=\"scriptManager\" runat=\"server\"\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 EnableCdn=\"True\" AjaxFrameworkMode=\"Disabled\" &gt;\r\n\u00a0\u00a0 &lt;Scripts&gt;\r\n\u00a0\u00a0\u00a0 &lt;asp:ScriptReference \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Paththth=\"http:\/\/ajax.microsoft.com\/ajax\/jquery\/jquery-1.4.1-vsdoc.js\" \/&gt;\r\n\u00a0\u00a0 &lt;\/Scripts&gt;\r\n&lt;\/asp:ScriptManager&gt;\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>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.<\/p>\n<h1>Writing The Client-Side Code<\/h1>\n<p>To allow the client to get a sentence from the server asynchronously, we first put a Button and a TextBox on the web page. We assign the <b>btGet <\/b>\u00a0value to the button&#8217;s id property and the <b>txtSentence<\/b> value to the analog TextBox&#8217;s id property.<\/p>\n<p>We want a new sentence to be retrieved from the web server and then displayed inside the TextBox whenever the user clicks on the button.<\/p>\n<p>The AJAX request doesn&#8217;t make use of\u00a0 a postback of the page: \u00a0instead,\u00a0 it uses JavaScript code to begin the request. So, we create a JavaScript function on the client and let the<b> onclick<\/b> event of the button invoke it:<\/p>\n<pre class=\"lang:xhtml theme:github\">&lt;input id=\"btGet\" type=\"button\" \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 value=\"button\" onclick=\"javascript:getSentence()\" \/&gt;\r\n<\/pre>\n<p>The <b>getSentence<\/b> JavaScript function must contain the code needed to get a sentence form the server, using JQuery.<\/p>\n<p>For this to happen, we use the <b>.ajax()<\/b> method of the main JQuery object <b>$<\/b>. This method accepts, as input, a JavaScript object that has all the elements that are needed to perform an AJAX call to the server.\u00a0 We don&#8217;t need all of them and so we&#8217;ll only describe here \u00a0the most commonly used.<\/p>\n<p>For a full list, see the JQuery documentation at <a href=\"http:\/\/api.jquery.com\/jQuery.ajax\/\">jQuery.ajax (settings)<\/a><\/p>\n<p><b>url:<\/b> 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.<\/p>\n<p><b>data:<\/b> 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 \u00a0can be also be sent to the server by directly adding the query string to the url element.<\/p>\n<p><b>success:<\/b> 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 page&#8217;s 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.<\/p>\n<p><b>dataType:<\/b> This specifies the type of data expected by the client. It can be &#8216;html&#8217;, &#8216;text&#8217;, &#8216;xml&#8217;, &#8216;script&#8217;, &#8216;json&#8217; and &#8216;jsonp&#8217;. 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\u00a0 need explaining. \u00a0if we use the &#8216;script&#8217; value, \u00a0the method will expect some JavaScript code, if we use &#8216;json&#8217; (or the less known &#8216;jsonp&#8217;) \u00a0value, then the method will try to convert the response into a JavaScript object.<\/p>\n<p><b>error:<\/b> 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.<\/p>\n<p><b>complete:<\/b>If this is set,\u00a0 than the JavaScript function that you&#8217;ve specified will be invoked at the end of the process, after that the <b>success<\/b> or <b>error <\/b>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.<\/p>\n<p>Our <b>getSentence()<\/b> function will then look like this:<\/p>\n<pre class=\"lang:c# theme:vs2012\">&lt;script type=\"text\/javascript\"&gt;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 function getSentence() {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 $.ajax(\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 url: \"default.aspx\",\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 data: \"get=sentence\",\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 success: function (data)\r\n\u00a0{ $(\"#txtSentence\").get(0).value = data; },\r\nerror: function () { alert(arguments[2]); }\r\n\u00a0\r\n\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 });\u00a0 \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\r\n\u00a0\u00a0\u00a0 &lt;\/script&gt;\r\n<\/pre>\n<p>We have defined the callback function as an anonymous JavaScript function object and we have set the <b>success<\/b> element to its value. After the server response, this function will be invoked and its content will be executed. The function&#8217;s body shows what will happen. By using the JQuery function <b>$<\/b>, using as the selector the id of the TextBox, its value will be changed \u00a0to the value of the returned data.<\/p>\n<p>If an exception occurs, the error function will be invoked, and the exception&#8217;s 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 <b>arguments[2]<\/b> array item.<\/p>\n<p>You&#8217;ll notice that we decided to specify a value for the data element. This value will be sent to the server as a query string.\u00a0 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.\u00a0 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 &#8220;get&#8221; on its query string, an AJAX request was made, if it doesn&#8217;t, the page will respond as for normal GETs.<\/p>\n<p>So, on the OnLoad event of our web page we could write something like this:<\/p>\n<pre class=\"lang:c# theme:vs2012\">protected override void OnLoad(EventArgs e)  \r\n{  \r\n\u00a0  \r\n\u00a0\u00a0\u00a0 base.OnLoad(e);  \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 if (Request.QueryString[\"get\"] != null)\r\n\u00a0\u00a0\u00a0\u00a0{  \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Response.Clear();  \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Response.ContentType = \"text\/plain\";  \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Response.Write(GetSentence());  \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Response.End();  \r\n\u00a0\u00a0\u00a0\u00a0}  \r\n}  \r\n<\/pre>\n<p>If the query string contains a key named &#8220;get&#8221;, 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.<\/p>\n<p>After that, the callback function will be invoked on the client, passing the string as the value for the data argument. \u00a0As we have specified, the TextBox will be filled with the extracted value.<\/p>\n<p>You can download a copy of this example at the bottom of the article in the file &#8220;SupportingDocuments&#8221;.<\/p>\n<h1>Using \u00a0More Complex Data<\/h1>\n<p>We&#8217;ve shown you, in the previous example, how to perform an AJAX request of a string to a web server and how to use it to refresh a web page. In reality, things are usually more complex. Only rarely do you have to update your page with only a simple text. Normally, a mix of data must be refreshed instead. To be able to do so, we need to understand how to pass complex data to the client and how to use it to refresh the page.<\/p>\n<p>The most frequently used approach is to serialize our data using the JSON\u00a0 format and send the formatted string to the client for visualization. When data reach the client (with the callback invocation made by the server), JQuery is able to transform it in a JavaScript object that we can then use to refresh the page&#8217;s content.<\/p>\n<p>To illustrate this, we&#8217;ll\u00a0 suppose that we want to visualize on the client not only a randomly selected sentence, but also the ID of the same. To do this, we add a second TextBox to the default.aspx page, with ID given by <b>txtID<\/b>. It will show the ID related to the sentence.<\/p>\n<p>We need to modify the <b>GetSentence<\/b> method of the server in this way:<\/p>\n<pre class=\"lang:c# theme:vs2012\">private string GetSentence()  \r\n{  \r\n\u00a0\u00a0\u00a0 int index = new Random().Next(3);  \r\n\u00a0  \r\n\u00a0\u00a0\u00a0 XDocument doc = XDocument.Load(Server.MapPath(\"\/sentences.xml\"));  \r\n\u00a0\u00a0\u00a0\u00a0 \r\n\u00a0\u00a0\u00a0\u00a0var q = from s in doc.Descendants(\"sentence\")  \r\n\u00a0where (int)s.FirstAttribute == index select s;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \r\n\u00a0\u00a0\u00a0 StringBuilder sb = new StringBuilder();\r\n\u00a0\u00a0\u00a0 sb.Append(\"{\\\"id\\\":\\\"\");\r\n\u00a0\u00a0\u00a0 sb.Append(q.First&lt;XElement&gt;().Attribute(\"id\").Value);\r\n\u00a0\u00a0\u00a0 sb.Append(\"\\\", \\\"sentence\\\":\\\"\");\r\n\u00a0\u00a0\u00a0 sb.Append(q.First&lt;XElement&gt;().Value);\r\n\u00a0\u00a0\u00a0 sb.Append(\"\\\"}\");\r\n\u00a0\r\n\u00a0\u00a0\u00a0 return sb.ToString();\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \r\n}\r\n<\/pre>\n<p>This new method selects a sentence and then creates a JSON string that contains the id of the sentence in addition to the sentence&#8217;s text. The returned string will be something like this:<\/p>\n<pre>{\"id\":\"&lt;extracted_id&gt;\",\"sentence\": \"&lt;extracted_sentence&gt;\"}\r\n<\/pre>\n<p>Where the &lt;extracted_id&gt; and the &lt;extracted_sentence&gt; are the id and the text of the selected sentence.<\/p>\n<p>The OnLoad method of the page must be modified as follows:<\/p>\n<pre class=\"lang:c# theme:vs2012\">protected override void OnLoad(EventArgs e)  \r\n{\r\n\u00a0\u00a0\u00a0 base.OnLoad(e);\r\n\u00a0\u00a0\u00a0 if (Request.QueryString[\"get\"] != null)\r\n\u00a0\u00a0\u00a0\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Response.Clear();\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Response.ContentType = \"application\/json\";\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Response.Write(GetSentence());\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Response.End();\r\n\u00a0\u00a0\u00a0\u00a0}\r\n}\r\n<\/pre>\n<p>We have modified the content type of the response from text\/plain to application\/json.<\/p>\n<p>Finally, we change the JavaScript callback on the client in this way:<\/p>\n<pre class=\"lang:c# theme:vs2012\">&lt;script type=\"text\/javascript\"&gt;\r\n\u00a0\u00a0 function getSentence() {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0$.ajax(\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {  \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 url: \"default.aspx\",  \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 data: \"get=sentenct\",  \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \u00a0success: function (data) \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0{ $(\"#txtID\").get(0).value = data.id;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \u00a0$(\"#txtSentence\").get(0).value = data.sentence; },\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 error: function () { alert(arguments[2]); }  \r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 });  \r\n\u00a0\u00a0\u00a0\u00a0 }  \r\n&lt;\/script&gt;\r\n<\/pre>\n<p>The JQuery <b>.ajax() <\/b>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 <b>success <\/b>function. The created JavaScript object will have two properties: the <b>.id<\/b> properties with the id of the sentence and the <b>.sentence<\/b> property with the text of the same. This structure reflects the original JSON string structure. We use the two properties to update our page.<\/p>\n<h1>Improving the User-Experience<\/h1>\n<p>If you happen to use Microsoft AJAX and<b> UpdatePanels<\/b>, you probably know that Microsoft AJAX allows you to use a control named <b>UpdateProgress<\/b> to display some HTML code on the page immediately before the AJAX request and to hide it after \u00a0it has \u00a0completed.<\/p>\n<p>This allows us to display, for example, an animated gif while the user is waiting for the completion of the request.<\/p>\n<p>JQuery and its AJAX implementation allow you to perform the same thing, but by using some JavaScript code just before the AJAX request and just after the callback completion.<\/p>\n<p>This can improve the user-experience thanks to the fact that you can now use a more dynamic JavaScript code rather than static HTML to generate visual effects on the client.<\/p>\n<p>This can be done by using the following methods implemented on the JQuery library:<\/p>\n<p><b>.ajaxStart(fn):<\/b> Allows you to set a JavaScript callback-function to execute just before the AJAX request.<\/p>\n<p><b>.ajaxComplete(fn):<\/b> Specifies a JavaScript callback-function to execute just after the AJAX request completion.<\/p>\n<p>This methods are attached to each page&#8217;s element when they are selected with the main JQuery function <b>$.<\/b><\/p>\n<p>Returning to our example, we surround our two TextBoxes with a div tag: giving to it the value &#8216;<i>container<\/i>&#8216; for its id property.<\/p>\n<p>Although JQuery has a rich set of elements to perform animations of any type, we simply use the .<b>hide()<\/b> method to hide the TextBoxes just before the AJAX request, and the .<b>show()<\/b> method to show them again refreshed with the new values.<\/p>\n<p>We can set the two argument functions of the two methods on the <b>.ready()<\/b> method of the JQuery library. Remember that this method is executed after the completion of the loading of the page, when it is ready to operate.<\/p>\n<p>Our JavaScript code will be:<\/p>\n<pre class=\"lang:c# theme:vs2012\">&lt;script type=\"text\/javascript\"&gt;\r\n\u00a0\u00a0 $(document).ready\r\n\u00a0\u00a0\u00a0(\r\n\u00a0\u00a0\u00a0\u00a0\u00a0 function () {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 $(document).ajaxSend(function () { $(\"#container\").hide(\"normal\"); })\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 $(document).ajaxComplete(function () { $(\"#container\").show(\"normal\"); })\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\r\n\u00a0\u00a0 );\r\n&lt;\/script&gt;\r\n<\/pre>\n<p>If you run the application, the two TextBoxes will be hidden \u00a0after the button-click by reducing the div tag height to 0 with a speed given by the JQuery-defined value &#8216;n<i>ormal<\/i>&#8216;. 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.<\/p>\n<p>You can download a copy of this example at the bottom of the article in the file &#8220;SupportingDocuments&#8221;.<\/p>\n<h1>Conclusion<\/h1>\n<p>In this article we&#8217;ve 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\u00a0 without being limited to perform only a partial rendering of the page. Partial rendering allow us only to update server controls contained on some<b> UpdatePanel<\/b>. The update occurs when we change some properties of those controls on the \u00a0server side.\u00a0\u00a0 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.<\/p>\n<p>However, this doesn&#8217;t mean that ASP.NET <b>\u00a0UpdatePanels<\/b> 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 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 you&#8217;re looking for more configurable AJAX work, then \u00a0jQuery is a good library to consider.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>ASP.NET now has support for the jQuery JavaScript library. Although ASP.NET  integrated AJAX technology by introducing the is the UpdatePanel server control, jQuery offers an alternative, and more versatile, way of doing it and a great deal more besides. Matteo shows how easy it is to get started with using jQuery.&hellip;<\/p>\n","protected":false},"author":221869,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143538],"tags":[4143,4291,4156,4157,4242,4911,5189,4179],"coauthors":[11301],"class_list":["post-885","post","type-post","status-publish","format-standard","hentry","category-dotnet-development","tag-net","tag-ajax","tag-asp","tag-asp-net","tag-basics","tag-javascript","tag-matteo-slaviero","tag-source-control"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/885","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/221869"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=885"}],"version-history":[{"count":8,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/885\/revisions"}],"predecessor-version":[{"id":74853,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/885\/revisions\/74853"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=885"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=885"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=885"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=885"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}