Calling ASP.Net Code Behind using jQuery AJAX – A Simple Complete Example

Ajax (Asynchronous Javascript And XML) is a technique of sending the request to the server and receiving the response from the server without reloading the entire page. Consider a scenario where you have many Fields in your Web Form and you want to populate Field2 based on Field1 value. It would be overkill if you do postback and get that value from the server. You can use jQuery Ajax to call ASP.Net code behind to do the same which would result in better user experience.  Below picture explains the flow where we can send only the Field1 value using Ajax and get the calculated value from server.

ASP.Net jQuery Ajax

 

 

To explain the jQuery Ajax in ASP.Net, we are going to use a simple webform – screenshot pasted below

  1. You would enter any year in first text box
  2. Click the ‘Call method using Ajax’ button. This will call ASP.Net code behind using Ajax
  3. ‘Leap Year’ or ‘Not a Leap Year’ will be populated in result text box based on your input

 

Ajax Simple Form

To call the ASP.Net code behind method using jQuery Ajax, you need to do the following

  1. Define the ASP.Net code behind method so that it could be called from jQuery Ajax.
  2. Define a javascript function in which you would call jQuery Ajax function. You would pass the Aspx file name with method details(created in step 1) in url property of jQuery Ajax function
  3. Call the function (created in step 2) when button is clicked.

Let us discuss each of the above mentioned step in detail

1. Define the ASP.Net code behind method

  1. Below method would return true or false based on the year passed as input parameter. Please note that the ASP.Net code behind method should be annotated with [System.Web.Services.WebMethod] so that it can be called directly from ajax. SimpleAjax.aspx is the aspx filename in which this method is defined. This file name and the method name information is needed in step 2 – where we call jQuery Ajax function.

[System.Web.Services.WebMethod]

public static bool IsLeapYear(int year)

{

  return DateTime.IsLeapYear(year);

}

2. Define a javascript function in which you would call jQuery Ajax function

Before defining the function which uses jQuery Ajax, let us see the syntax of jQuery ajax so that we would know what each property or function denotes.

Below is the jQuery Ajax function syntax.

jQuery Ajax Syntax

 

In the first line of below function, we are calling e.preventDefault so that postback does not happen.  This line is not needed if we are using input type=”button” html element. But we are using asp:TextBox control which does postback by default, if clicked.

In success callback function, we are checking the returned value from Server side method. If its true, we would populating the result textbox as ‘Leap Year’. Else, we would populate ‘Not a Leap Year’. If there is any error, we would populate the same in result text box – handled via error callback function.


function callAjaxMethod(e) {

//To prevent postback from happening as we are ASP.Net TextBox control

//If we had used input html element, there is no need to use ' e.preventDefault()' as posback will not happen

  e.preventDefault();

  $.ajax({
    type: "POST",
    url: "SimpleAjax.aspx/IsLeapYear",
    data: '{year: "' + $("#<%=txtYear.ClientID%>").val() + '" }',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
      if (response.d) {
         $('#<%=txtIsLeapYear.ClientID%>').val('Leap Year');
      }
      else {
        $('#<%=txtIsLeapYear.ClientID%>').val('Not a Leap Year');
      }
    },
    failure: function (response) {
      $('#<%=txtIsLeapYear.ClientID%>').val("Error in calling Ajax:" + response.d);
    }
  });
}

3. Call the function (created in step 2) when button is clicked.

Call the function (defined in step 2) in OnClientClick of asp:Button


<asp:Button ID="btnAjax" runat="server" OnClientClick="callAjaxMethod(event)"  Text="Call method using Ajax" />

Below is the complete ASPX page markup – where most of the html table elements are primarily used for formatting.

Aspx Page Markup:


<form id="form1" runat="server">
  <div>
    <table>
       <tr>
          <td>Enter the year:</td>
          <td>
             <asp:TextBox ID="txtYear" runat="server"></asp:TextBox>
         </td>
      </tr>
      <tr>
         <td colspan="2">
           <asp:Button ID="btnAjax" runat="server" OnClientClick="callAjaxMethod(event)"  Text="Call method using Ajax" />
        </td>
      </tr>
   </table>
  </div>
  <div>
    <table>
      <tr>
         <td>Result:</td>
           <td><asp:TextBox ID="txtIsLeapYear" runat="server"></asp:TextBox></td>
      </tr>
    </table>
  </div>
</form>

Thanks for reading the article. If you like this article, please subscribe in the below form.

 


Posted

in

, ,

by

Tags: