Reader Level:
ARTICLE

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

Posted by Akkiraju Ivaturi Articles | ASP.NET Programming January 16, 2013
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.
  • 1
  • 0
  • 10517

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.

Purpose

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.

<body>

    <form id="form1" runat="server">

    <div>

        <asp:GridView ID="ShowProducts" runat="server" AutoGenerateColumns="false">

            <Columns>

                <asp:TemplateField HeaderText="Product Name Using Load">

                    <ItemTemplate>

                        <asp:LinkButton ID="LinkProducts" runat="server" myCustomID='<%# Eval("ID")%>' Text='<%# Eval("Name")%>'></asp:LinkButton>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Product Name Using Get">

                    <ItemTemplate>

                        <asp:LinkButton ID="GetProducts" runat="server" myCustomID='<%# Eval("ID")%>' Text='<%# Eval("Name")%>'></asp:LinkButton>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:BoundField DataField="Description" HeaderText="Description" />

            </Columns>

        </asp:GridView>

    </div>

    <div id="DisplayDetails">

    </div>

    </form>

</body>

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

        /// <summary>

        /// Page Load Event

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        protected void Page_Load(object sender, EventArgs e)

        {

            List<Product> ProductList = new List<Product>

            {

new Product(){Name="Product1", ID="1",Description = "Description1"},

new Product(){Name="Product2", ID="2",Description = "Description2"},

new Product(){Name="Product3", ID="3",Description = "Description3"}

            };

 

            ShowProducts.DataSource = ProductList;

            ShowProducts.DataBind();

        }

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:

<%@ Page Language="C#" %>

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)

    {

        string productID = Request.QueryString["productID"];

       

  Response.Write("<table width='95%' border='0' cellpadding='0'    cellspacing='0' align='center'>");

        Response.Write("<tr class='tdcolbg'>");

        Response.Write("<td>");

        Response.Write("You have clicked :" + productID);

        Response.Write("</td>");

        Response.Write("</tr>");

        Response.Write("</table>");

 

 

        Response.End();

    }

</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:

<script type="text/javascript" src="JS/jquery.js"></script>

 

    <script type="text/javascript">

$(document).ready(function() {

   jQuery('[id$="LinkProducts"]').click(function() {

   var customID = $(this).attr('myCustomID');

   $('#DisplayDetails').load("ShowProductDetails.aspx?productId="+customID);

   return false;

        });

                

    });

 

    </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:

jQuery('[id$="LinkProducts"]')

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:

<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:
 

jQuery('[id$="GetProducts"]').click(function() {

   var customID = $(this).attr('myCustomID');

   $.get("ShowProductDetails.aspx",{ productId: "" + customID + ""},

   function(data)

   {

   $('#DisplayDetails').html(data);

   

   });

  return false;

        });

       

    });

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.
 

<script type="text/javascript">

$(document).ready(function() {

   jQuery('[id$="LinkProducts"]').click(function() {

   var customID = $(this).attr('myCustomID');

   $('#DisplayDetails').load("ShowProductDetails.aspx?productId="+customID);

   return false;

        });

       

        jQuery('[id$="GetProducts"]').click(function() {

   var customID = $(this).attr('myCustomID');

   $.get("ShowProductDetails.aspx",{ productId: "" + customID + ""},

   function(data)

   {

   $('#DisplayDetails').html(data);

   

   });

  return false;

        });

       

    });

 

    </script>

Conclusion

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!!!
 

COMMENT USING

Trending up