Gaz
Gaz

Reputation: 11

How to send json object to C# web server

I write this java script to send json object to c# web service. but its not work..Why is it? this is my javascript..

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery- 1.5.1.js"></script>

<script type="text/javascript">
     function BindJson() {

 document.getElementById("demo").innerHTML=Date();
        $.ajax({
            type: "POST",
            url: "Service1.asmx/SerializeJson",
            data: JSON.stringify({ person:{ firstName: "Denny" }}),

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

            success: function (data2) {
              alert(data2.d);
            },
            error: function (request, status, errorThrown) {
                alert(status);
            }
        }); 
   } 
</script>

And this is my server class ..

 [System.Web.Script.Services.ScriptService]
 public class Service1 : System.Web.Services.WebService
 {
    [WebMethod]
    public string SerializeJson(Person person)
    {
        return "Success";
    }
    public class Person
    {
        public string firstName { get; set; }   
    }   
 }

Upvotes: 0

Views: 3176

Answers (2)

Akash Kava
Akash Kava

Reputation: 39916

You should not use JSON.stringify because when you specify content type of JSON, jQuery will convert it using JSON.stringify.

        data: JSON.stringify({ person:{ firstName: "Denny" }}),

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

Change it to

        data: { person:{ firstName: "Denny" }},

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

Also you don't need to send person as a member of object unless it is required.

        data: { firstName: "Denny"},

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

Upvotes: 1

Patrick Evans
Patrick Evans

Reputation: 42736

data option for .ajax expects a name value pair string, or an object

data: { "myjson": JSON.stringify({ person:{ firstName: "Denny" }}) },
//OR
data: "myjson="+JSON.stringify({ person:{ firstName: "Denny" }}),
//Or just send the data values and retrieve in the way you get GET or POST variables in C#
data: { person:{ firstName: "Denny" }},

Upvotes: 0

Related Questions