0

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; }   
    }   
 }

2 Answers 2

1

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",
Sign up to request clarification or add additional context in comments.

Comments

0

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" }},

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.