In this article we will explore how to send json array of objects to pagemethod. The pagemethod will have objet of List as parameter to accept json array of objects.
Let's write some code to achieve this.
Step 1: Create a class Employees
public class Employees { private string name; private int age; private string address; public string Name { get { return name; } set { name = value; } }
public int Age { get { return age; } set { age = value; } }
public string Address { get { return address; } set { address = value; }
} }
Step 2: Create a method AddEmployees which accepts List<Employees>
[WebMethod] public static void AddEmployees(List<Employees> objEmployees) {
}
Step 3: Add below javascript files in the head section of aspx page.
<script src="jquery-1.4.2.min.js" type="text/javascript"></script> <script src="json2.js" type="text/javascript"></script>
Download jQuery
Download json2
Step 4: Create an Array which will hold the objects, then create object with property which has been defined in the class Employees in step1. Finally stringify using JSON.stringify to get json and send it to the page method.
var objEmployees = new Array(); var objEmployee = {}; objEmployee.Name = "John"; objEmployee.Age = "20"; objEmployee.Address = "Address of John"; objEmployees[0] = objEmployee;
objEmployee = {}; objEmployee.Name = "Andrew"; objEmployee.Age = "30"; objEmployee.Address = "Address of Andrew"; objEmployees[1] = objEmployee;
var json = JSON.stringify({ "objEmployees": objEmployees }); $.ajax({ type: "POST", url: "jQuerySerializeArray.aspx/AddEmployees", data: json, contentType: "application/json; charset=utf-8", dataType: "json", failure: function(errMsg) { $("#errMessage").text(errMsg); } });
This ends the article of sending json array of object to pagemethod.
|