Saturday 27 August 2011

Sending class object in json request

below article describes that how to send an object in json request Instead of list of parameters.

below is the aspx page code for input fields.
Emp ID
Emp Name



below is the java script function to get form values.
Function baigFunc() {                    
            var _X = {};

Note: below "EmpId" and "EmpName" are class Properties. 
Get all values you required and add them in array.
send array object in json request.

            _X["EmpId"] = $("input[id$='txtEmpID']").val(); 
            _X["EmpName"] = $("input[id$='txtEmpName']").val();
            var request = "{'obj':" + JSON.stringify(_X) + "}";

            $.ajax({
                type: "POST",
                url: "pageName.aspx/TestFunc",
                data: request,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: callSucess
            });
        }
        function callSucess() {
            alert('Sucessfull');
        }
below is the code for serverside.

[WebMethod]
    public static void TestFunc(BaigClass obj)
    {     
        var empId = obj.EmpId; 
        var empName = obj.EmpName;
    }
Below is the class for getting values
public class BaigClass
{
    public string EmpId { get; set; }
    public string EmpName { get; set; }
} 


this is the best solution for sending values on server side when you have many input fields on form because this will take so much time to define variables and sending them in jSon request.

No comments:

Post a Comment