如何将json对象发送到C#Web服务器

时间:2013-08-04 09:57:46

标签: c# javascript json

我编写这个java脚本来将json对象发送到c#web服务。但它不起作用。为什么? 这是我的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>

这是我的服务器类..

 [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 个答案:

答案 0 :(得分:1)

您不应该使用JSON.stringify,因为当您指定JSON的内容类型时,jQuery将使用JSON.stringify对其进行转换。

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

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

将其更改为

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

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

除非有必要,否则您不需要将人员作为对象的成员发送。

        data: { firstName: "Denny"},

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

答案 1 :(得分:0)

data

.ajax选项需要名称值对字符串或对象

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