Wednesday 3 April 2013

ASP.NET C# Method call using AJAX jQuery




Hi Friends,

In this article I will show you how to call an ASP.NET C# method (Web Method) using jQuery.

Step 1: Create a Web Application

Step 2: In WebForm1.aspx include jQuery file as given below. If you do not have jQuery file, you can download the latest files from http://jquery.com/

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>




Step 3: 


In code behind page (WebForm1.aspx.cs) create a web method to return some data as given below. Make sure to add the attribute [WebMethod()] to the function. You have to include the namespace System.Web.Services. (using System.Web.Services;)

Add a web method in your page as mentioned below.

   [WebMethod]
        public static string GetAllEmpName()
        {
        Employee objEmployee = new Employee { Name = "Sujeet", EmpSal = "50,000", Id = 82375 };


            return "Parameter sent to server from client side as " +
           "follows:<br/>First Name => " +
           objEmployee.Name + "<br/>Emp Sal => " +
           objEmployee.EmpSal + "<br/>Id=> " +
           objEmployee.Id + "<br/>Address => " + objEmployee.Address;
        }

This method returns All Employees from database or collection

Step 4

We will use a jQuery "Ajax" method to call, page methods.

<script type="text/javascript">
$(document).ready(
    function () {
    try {
        $('#btnTest3').click
        (
    function () {
     $.ajax(
    {
    type: "POST",
    url: "AJAXCalling.aspx/GetAllEmpName",
    data: "{}",
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    async: true,
    cache: false,
    success: function (msg) {

        $('#myDiv3').text(msg.d); alert(msg.d);
    },
    error: function (x, e) {
        alert("The call to the server side failed. " + x.responseText);
    }
    });
        return false;
    });
    }

    catch (err) {
        alert(err);
    }
    });
   
    </script>



Step 5:

In the Html page we will add div and button like

   <asp:Button ID="btnTest3" runat="server" Text="Click Me"   />
  
<div id="myDiv3" style="font-family:Arial; color: Red;"/>


Run the application and click the button, you can see that the webmethod is called and data is returned.


Happy Programming!!
Don’t forget to leave your feedback and comments below!
If you have any query mail me to Sujeet.bhujbal@gmail.com     
Regards
Sujeet Bhujbal
--------------------------------------------------------------------------------
----------------------------------------------------------------------------------

No comments:

Post a Comment