pavanarya

Let us share the knowledge

Calling a webservice using Jquery and passing jsonarray object

with 6 comments

Hi,
In this post i want to write about Json array and passing json array to a web service using Jquery.

What is Json

According to Json.org. Json is defined as follow

“JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate”

It is a key value pair way of exchanging data
Json format looks like this.

{"d":"Hello World"}//Simple Json string

//Json array
{"classroom":
[
{"RollNum":0,"Name":"Pavan Kumar Aryasomayajulu","Branch":"IT"},
{"RollNum":1,"Name":"Kiran Mantri","Branch":"IT"},
{"RollNum":2,"Name":"Sri Harsha varada","Branch":"IT"}
]
}

In the above example the first sample defines a simple json string that contains a key value pair of data.

In the second example we are forming a json array that represents student info present inside a class.

What i am going to do in this post

1.Actually in this post i want to create a json array in the javascript.
2.I am going to have a button in the aspx page.
3.When we click on the button i am going to call the web method present inside a web service using jquery and then i’ll pass the json array created to the webmethod.

First let me create a web service

TestJson.asmx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace JsonArrayToWebService
{
    /// <summary>
    /// Summary description for TestJson
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
     [System.Web.Script.Services.ScriptService]
    public class TestJson : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
        public string DisplayClassRoom(List<ClassRoom> classroom)
        {
            //Perform operations on List of classroom objects
            return "Hello World";
        }
    }

    public class ClassRoom
    {
        public int RollNum { get; set; }
        public string Name { get; set; }
        public string Branch { get; set; }
    }
}

In the above code,

I am creating a class with the name ClassRoom and it contains few properties like RollNum,Name,Branch.
I am having a webmethod called DisplayClassRoom. This method accepts list of classroom objects.

Please don’t forget to uncomment this line

     [System.Web.Script.Services.ScriptService]

javascript array and push method

In javascript we can create an array in two ways.

var arrayobj=new Array();

var arrayobj1=[]

In the above code piece we are creating an empty array.

var arrayObj=["pavan","kiran","Rajesh"];

arrayObj.push("Harsha");
arrayObj.push("Praveen");

for (var k = 0; k <= arrayObj.length; k++) {
   alert(arrayObj[k]);
}

So in the above sample we are creating an array with values pavan,kiran and rajesh.

We are adding extra values to that using push() method. Push method is used to append values to a array.

Creating Json array

                  var JSONObject = new Array();

                  for (var i = 0; i < 4; i++) {
                     var obj=new Object();
                     obj.RollNum=i;
                     obj.Name="Pavan Kumar Aryasomayajulu";
                     obj.Branch="IT";
                    JSONObject.push(obj);
                    }

In the above example we are creating an object using new Object();
In javascript we can create properties on the fly and assign values to it directly.

At the same time i am creating a array using new Array(); And i am adding the object created (obj) to the array (JSONObject) in the for loop.

So our JSONObject array contains object which contains Rollnum,Name and Branch.

So we are having an array of objects. In order to convert that to json string we are supposed to use Json.Stringify()

JSON.stringify(JSONObject);

//it returns below data
{
[
{"RollNum":0,"Name":"Pavan Kumar Aryasomayajulu","Branch":"IT"},
{"RollNum":1,"Name":"Pavan Kumar Aryasomayajulu","Branch":"IT"},
{"RollNum":2,"Name":"Pavan Kumar Aryasomayajulu","Branch":"IT"}
]}

Calling Webservice using jquery


                    $.ajax({
                        type: "POST",
                        url: "TestJson.asmx/FormatClassRoom",
                        data: JSON.stringify({classroom:JSONObject}),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {}
                    });

So in the above code piece we are making use of $.ajax() method present inside jquery.
It accepts few parameters:
1.Type: either get or post
2.url: relative url of the service an web method.
3.data:actual data to be sent.
4.contentType: MIME type of data we are supposed to send.
5.datatype: datatype of the data like text or xml or json
6.Success: callback function that is executed after successful execution of webmethod.

JSON.stringify({classroom:JSONObject})

Note we are supposed to use {classroom:JSONObject} because the json array data(JSONObject) is deserialized into a format that represents object of the class Classroom present inside web service.

classroom specifies the input parameter of the webmethod DisplayClassRoom(List classroom)

Note:The parameter name and Json object name should match.(classroom)

Properties present inside the ClassRoom class and the properties we are adding to json array should have same names.

Complete Code

TestJson.asmx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace JsonArrayToWebService
{
    /// <summary>
    /// Summary description for TestJson
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
     [System.Web.Script.Services.ScriptService]
    public class TestJson : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
        public string DisplayClassRoom(List<ClassRoom> classroom)
        {
            //Perform operations on List of classroom objects
            return "Hello World";
        }
    }

    public class ClassRoom
    {
        public int RollNum { get; set; }
        public string Name { get; set; }
        public string Branch { get; set; }
    }
}

CallService.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CallService.aspx.cs" Inherits="JsonArrayToWebService.CallService" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
           	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function pavan() {

                var JSONObject = new Array();

                  for (var i = 0; i < 4; i++) {
                     var obj=new Object();
                     obj.RollNum=i;
                     obj.Name="Pavan Kumar Aryasomayajulu";
                     obj.Branch="IT";
                    JSONObject.push(obj);
                    }

        $.ajax({
            type: "POST",
            url: "TestJson.asmx/FormatClassRoom",
            data: JSON.stringify({ classroom: JSONObject }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {

            }
        });
            }

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type=button onclick="pavan()" name="Button1" value="Button1" />
    </div>
    </form>
</body>
</html>

About these ads

Written by pavanarya

September 9, 2012 at 12:36 pm

6 Responses

Subscribe to comments with RSS.

  1. Great Help. Thnx

    newbie

    November 4, 2012 at 10:32 am

  2. this is not working…jquery not calling the webmethod
    Body = $(“[id$=boxArea]”);
    var AgentIDs = [];
    var strAgentIDs = “”;
    for (var i = 0; i < $('.itemListClassTLADD li').length; i++) {
    var TLid = $('.itemListClassTLADD li')[i].value;
    var AgentUL = $('.itemListClassTLADD li').parent()[i].id;
    var aUl = AgentUL.split('_');
    $('#boxList_' + aUl[1]).find('li').each(function (v, g) {
    var obj = new Object();
    obj.TLID = TLid;
    obj.AgentID = this.value;
    AgentIDs.push(obj);
    // AgentIDs.push({"TLID":TLid,"AgentID": this.value});
    });
    }
    $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "WebService2.asmx/SAve",
    data: JSON.stringify({ SaveRecords: AgentIDs }), //"{'Records': '" + JSON.stringify({ "SaveRecords": AgentIDs }) + "'}",
    dataType: "json",
    // async: true,
    success: function (data) {
    alert("yes");
    },
    error: function (result) {
    alert("Error");
    }
    });

    and my webservice WebService2.asmx code:-

    public class SaveRecords
    {
    public stringTLID { get; set; }
    pulcsr string AgentID { get; set; }
    }
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string SAve(List Records)
    {
    return “fdf”;

    //int TL = Convert.ToInt16(TLID);
    //int result = obj.SaveAgentassigned(TL, AgentIds);

    }

    please help me where i am wrong

    lalit

    November 15, 2012 at 3:03 pm

    • Hi Lalit,
      I feel everything seems to be good with js code. The only thing that i suspect is

      may be you are missing
      ” [System.Web.Script.Services.ScriptService]” on your webservice. By default this line is commented in your asmx.cs file and you can uncomment it. This particular attribute makes sure that our webservice is accessible from js file.

      Also if you don’t mind can you email me your source code(complete) so that i can investigate further and help you out.
      My email id is “pavan.aryasomayajulu@gmail.com”

      Thanks,
      Pavan

      pavanarya

      November 15, 2012 at 8:36 pm

  3. hi ,when i click on the button its just showing empty page,with the same code as shown above

    sesh

    January 4, 2013 at 1:17 pm

  4. Great ,,Works Like a Miracle ,,thanks a lot :)

  5. Thanks man this example works nicely. This is a wonderful example with good explanation. Thanks a lot.

    Hemachandhiran H

    August 21, 2014 at 12:24 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: