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

How to send json object to C# web server

本文关键字:C#web 服务器 对象 json      更新时间:2023-09-26

我编写了这个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; }   
    }   
 }

您不应该使用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",
.ajaxdata选项需要名称-值对字符串或对象
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" }},