Invoke Server Side Method which Accepts a Class Object via Ajax

In this blog I shall demonstrate how to call server side methods with custom parameters as input and output.

Before going through this article I recommend to go through the basics of jquery. There are lots of articles in c-sharpcorner.com.

Step 1: Create a custom Class named Employee.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace MethodInvocation

{

    public class Employee

    {

        public string  FirstName { get; set; }

        public string LastName { get; set; }

        public string FullName { get; set; }

    }

}

Step 2: Design a web form with two textbox and a button as shown

<body>

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

    <div>

   First Name :<input type="text" id="txtFirstName" />

    <br />

    <br />

    Last Name :<input type="text" id="txtLastName" />

    <br />

    <br />

   <asp:Button ID="btnAdd" runat="server" Text="Get Full Name" Width="100px" />

    </div>

    </form>

</body>

 
 

Step 3: Implement the Web Method.

[WebMethod]

public static Employee GetFullName(Employee employee)

{

    Employee emp=employee;

    emp.FullName = string.Concat(emp.FirstName, "  ", emp.LastName);

    return emp;           

}

Step 4: Implement the button click event

   <script type="text/javascript">

        var employee;

        $(document).ready(function () {\ 

            $("#btnAdd").click(function () { 

                var employee = {};

                employee.FirstName = $("#txtFirstName").val();

                employee.LastName = $("#txtLastName").val(); 

                $.ajax({

                    type: "POST",

                    url: "Invoke.aspx/GetFullName",

                    data: "{employee:" + JSON.stringify(employee) + "}",

                    contentType: "application/json; charset=utf-8",

                    dataType: "json"

                       success: function (result) {

                        alert("Welcome" + " "+ result.d.FullName);                       

                    },

                    error: function (error) { alert(error.d) }

                }); 

            }); 

        });

    </script>

We need to pass an Employee object to the GetFullName Web Method.

For that purpose create an object as shown below.

var employee = {};

employee.FirstName = $("#txtFirstName").val();

employee.LastName = $("#txtLastName").val();

Now this employee object sis passed as the data in the Ajax code.

data: "{employee:" + JSON.stringify(employee) + "}"

For a better understanding I have uploaded the source code.

Output