Easiest way to jQuery Ajax call in ASP.NET

This article is all about calling an Ajax request to an ASP.NET based website. Most efficient and easiest way to implement Ajax request-response flow in ASP.NET is using Web-Method. Basically, as in general if we require to call ajax in .NET then either we create a new webpage for serving that request separately or we create a Web-Service for the same.

Lets get-rid-of these solutions because we do have a better one in place. Actually suggested solution is mixture of both with more flexibility and stability:-

This implementation has following easy steps to implement. Lets consider the same with an example:

  1. Create a ASP.NET Website.
  2. Add a webpage say “Default.aspx” and set as start-up page.
  3. Include jQuery reference in you aspx page.
    <script src="Scripts/jquery-1.9.0.js" type="text/javascript"></script>
    
  4. In your code behind file of Default.aspx i.e. Default.aspx.cs, include a NameSpace as follows:

    using System.Web.Services;
    
  5. In your code behind file of Default.aspx i.e. Default.aspx.cs, Create a WebMethod as a public Static. It should be static so that easily can be called with URL publicly like http://localhost/default.aspx/testajax :

    [WebMethod()]
    public static string testajax(int testParam)
    {
        /*You can do database operations here if required*/
        return "testParam is" + testParam.ToString();
    }
    

    That’s all for code behind.

  6. Now prepare you frontend to send and receive ajax using script:

     
    function syncToServerViaAjax(param) {
        jQuery.ajax({
     url: 'Default.aspx/testajax',
     type: "POST",
     data: "{'testParam':" + param+ "}",
     contentType: "application/json; 
    charset=utf-8",
     dataType: "json",
     success: function (data) {
         alert(data.d);
     }
    
        });
    }
    
    
  7. now you can call this function on any specific event and to process data. As:

    Add a button into HTML:

    <button  onclick="syncToServerViaAjax(2)">Click</button>
    

That’s All about handling Ajax in ASP.NET. Do let me know your thoughts as well queries on the same. Thanks.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>