Calling Server Side Function From Link Button Using AJAX and jQuery in ASP.NET

This article explains how to execute a server-side function using AJAX and jQuery when the link button is clicked. Here the call to the server-side code is handled from the client side.

Note: I am providing examples using a Link Button for calling and executing a method through HTTP without post-back. In practice, you may extend this example for any other ASP.NET controls as per the requirements.


To call a server-side function from the client side using AJAX and jQuery.

Here is my UI code

Note that we have added two Link Buttons to display the Product Names. One of the buttons requests a response from the remote file using the jQuery load() function and the other one uses the $.get() method. We will see how to write functions for both of these buttons soon.

  1. <body>  
  2.     <form id="form1" runat="server">  
  3.     <div>  
  4.         <asp:GridView ID="ShowProducts" runat="server" AutoGenerateColumns="false">  
  5.             <Columns>  
  6.                 <asp:TemplateField HeaderText="Product Name Using Load">  
  7.                     <ItemTemplate>  
  8.                         <asp:LinkButton ID="LinkProducts" runat="server" myCustomID='<%# Eval("ID")%>' Text='<%# Eval("Name")%>'></asp:LinkButton>  
  9.                     </ItemTemplate>  
  10.                 </asp:TemplateField>  
  11.                 <asp:TemplateField HeaderText="Product Name Using Get">  
  12.                     <ItemTemplate>  
  13.                         <asp:LinkButton ID="GetProducts" runat="server" myCustomID='<%# Eval("ID")%>' Text='<%# Eval("Name")%>'></asp:LinkButton>  
  14.                     </ItemTemplate>  
  15.                 </asp:TemplateField>  
  16.                 <asp:BoundField DataField="Description" HeaderText="Description" />  
  17.             </Columns>  
  18.         </asp:GridView>  
  19.     </div>  
  20.     <div id="DisplayDetails">  
  21.     </div>  
  22.     </form>  
  23. </body> 

We are going to use the same server-side code for populating the GridView; it is:

  1. /// <summary>  
  2. /// Page Load Event  
  3. /// </summary>  
  4. /// <param name="sender"></param>  
  5. /// <param name="e"></param>  
  6. protected void Page_Load(object sender, EventArgs e)  
  7. {  
  8.     List<Product> ProductList = new List<Product>  
  9.     {  
  10.         new Product(){Name="Product1", ID="1",Description = "Description1"},  
  11.         new Product(){Name="Product2", ID="2",Description = "Description2"},  
  12.         new Product(){Name="Product3", ID="3",Description = "Description3"}  
  13.     };  
  14.     ShowProducts.DataSource = ProductList;  
  15.     ShowProducts.DataBind();  
  16. } 

If you run the code, you will see the screen as in the following:

Image 1.jpg

In this example, we will be going through how to call server-side code from the client side using AJAX and jQuery. jQuery has a method called "load ()" which loads HTML from a remote file and adds the response content to the control.

To keep it simple, we are going to add a file to the project with an extension ".aspx" with no code behind. The purpose of this file is to provide a response to the AJAX call, so no UI is required. So, clear the entire HTML portion of the file and add the following code:

  1. <%@ Page Language="C#" %>  
  2. <script runat="server">  
  3.     protected void Page_Load(object sender, EventArgs e)  
  4.     {  
  5.         string productID = Request.QueryString["productID"];  
  6.         Response.Write("<table width='95%' border='0' cellpadding='0'    cellspacing='0' align='center'>");  
  7.         Response.Write("<tr class='tdcolbg'>");  
  8.         Response.Write("<td>");  
  9.         Response.Write("You have clicked :" + productID);  
  10.         Response.Write("</td>");  
  11.         Response.Write("</tr>");  
  12.         Response.Write("</table>");  
  13.         Response.End();  
  14.     }  
  15. </script> 

This file uses <script runat="server">. It takes the value of the productId from the query string and builds the response to be displayed.

Now let us see how to load the HTML content of the aspx file in the div tag of the UI using AJAX and jQuery.

Add a reference to the jQuery file in the JS folder of the application and reference it in your main ASPX page where we are going to call the remote file (.aspx) and display the content. You can check the attached project for the article to understand the code better.

Add the following function in the <head></head> tags:

  1. <script type="text/javascript" src="JS/jquery.js"></script>  
  2.     <script type="text/javascript">  
  3. $(document).ready(function() {  
  4.    jQuery('[id$="LinkProducts"]').click(function() {  
  5.    var customID = $(this).attr('myCustomID');  
  6.    $('#DisplayDetails').load("ShowProductDetails.aspx?productId="+customID);  
  7.    return false;  
  8.         });  
  9.     });  
  10. </script> 

Explanation of the above method: As the page is loaded, "$(document).ready()" is applied to the Link Button click event. Next, if we see that the script has:


which is used to get the ID of the Link Button that is clicked. This is because when the page is rendered, the id of the server-side controls is changed, so we cannot guess the form of the id. Also, the Link Buttons are rendered as anchor tags as in the following:

  1. <a id="ShowProducts_ctl02_LinkProducts" myCustomID="1" href="javascript:__doPostBack('ShowProducts$ctl02$LinkProducts','')">Product1</a>
Since the DIV tag is not decorated to be run at the server, we can directly refer to the DIV tag by #DIV tag ID. You can access the attribute of the control using "control.attr(attribute)".

When the user clicks the link, the function above is called and it reads the myCustomID property's value and then makes an AJAX call to the aspx page and gets the response and binds the response to the DIV tag. To check this put a break point in the aspx file added for sending the response and see how it is called by the jQuery as in the following:

Click on the Product name and check if the request is sent to the asp file.

Image 2.jpg

After the execution, you will see the output as in the following:

Image 3.jpg

You can also get the response using the get method instead of load method and bind the data to the DIV tag. The function now will be as in the following:

  1. jQuery('[id$="GetProducts"]').click(function() {  
  2.    var customID = $(this).attr('myCustomID');  
  3.    $.get("ShowProductDetails.aspx",{ productId: "" + customID + ""},  
  4.    function(data)  
  5.    {  
  6.    $('#DisplayDetails').html(data);  
  7.    });  
  8.   return false;  
  9.         });  
  10.     });

The $.get() method is the same as the load method with the only exception that the callback argument specifies what is to be done with the response from the AJAX request.

Let us club these two methods in the $(document).ready() so that the same can be used to add the event to the two Link Buttons.

  1. <script type="text/javascript">  
  2. $(document).ready(function() {  
  3.    jQuery('[id$="LinkProducts"]').click(function() {  
  4.    var customID = $(this).attr('myCustomID');  
  5.    $('#DisplayDetails').load("ShowProductDetails.aspx?productId="+customID);  
  6.    return false;  
  7.         });  
  8.         jQuery('[id$="GetProducts"]').click(function() {  
  9.    var customID = $(this).attr('myCustomID');  
  10.    $.get("ShowProductDetails.aspx",{ productId: "" + customID + ""},  
  11.    function(data)  
  12.    {  
  13.    $('#DisplayDetails').html(data);  
  14.    });  
  15.   return false;  
  16.         });  
  17.     });  
  18. </script> 


To make the example simple I have used an aspx file to respond to the AJAX call. In real-world situations, we will be calling a Web Service to provide the response. In the next article, we will see how to call an ASP.NET Web service.

Again, I would like to reiterate that you can extend this example for other ASP.NET controls for mouse over, click and any other event. This basically avoids the page post-back and helps invoke the server-side code.

Happy Coding!!!