【问题标题】:How to pass JSON object using Ajax with ASP.NET WebMethod如何使用 Ajax 和 ASP.NET WebMethod 传递 JSON 对象
【发布时间】:2012-11-07 02:23:27
【问题描述】:

我在使用 Ajax 和 ASP.NET WebMethods 传递 JSON 对象时遇到问题

function setStudentInfo() {
    var jsonObjects = [
        { id: 1, name: "mike" },
        { id: 2, name: "kile" },
        { id: 3, name: "brian" },
        { id: 1, name: "tom" }
    ];

    $.ajax({
        type: "POST",
        url: "ConfigureManager.aspx/SetStudentInfo",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        data: { students: JSON.stringify(jsonObjects) },
        success: function (result) {
            alert('success');
        },
        error: function (result) {
            alert(result.responseText);
        }

    });
}

ASP.NET 代码

[WebMethod]
public static void SetStudentInfo(object students)
{
     //Here I want to iterate the 4 objects and to print their name and id
}

我收到以下错误:

"{"Message":"无效的 JSON 原语:学生。","StackTrace":" 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 深度) 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(字符串输入,Int32 depthLimit,JavaScriptSerializer 序列化程序) 在 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer 序列化程序,字符串输入,类型类型,Int32 depthLimit) 在 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](字符串输入) 在 System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext 上下文,JavaScriptSerializer 序列化程序) 在 System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData 方法数据,HttpContext 上下文) 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}"

【问题讨论】:

  • 您遇到了什么问题(更具体地说)?

标签: asp.net ajax json jquery


【解决方案1】:

我知道这是一个老问题,但如果有人来这里寻求答案,这就是解决方案;

var jsonObjects=[
    { id: 1, name: "mike" },
    { id: 2, name: "kile" },
    { id: 3, name: "brian" },
    { id: 1, name: "tom" }
];

$.ajax({
    type: "POST",
    url: "ConfigureManager.aspx/SetStudentInfo",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: false,
    data: JSON.stringify({ students: jsonObjects }),
    success: function (result) {
        alert('success');
    },
    error: function (result) {
        alert(result.responseText);
    }

});

【讨论】:

    【解决方案2】:

    将整个 JSON 作为字符串传递,如下所示:

    data: '{variable: "value"}'
    

    如果我像你一样尝试通过它,我总是会得到一个错误。

    【讨论】:

    • 键也需要引用。
    【解决方案3】:

    您收到该错误是因为需要一个对象,但您的代码需要一个对象列表。有时这可能有点棘手。为了使数据传输更容易,您应该创建一个具有要传递给 WebMethod 的对象类型的属性的类,因为 ASP.NET 似乎更容易解析它。例如:

    public class Student
    {
        private string _name;
        private int _id;
        public string name {
            get { return _name; }
            set { _name = value; }
        }
        public int id {
            get { return _id; }
            set { _id = value; }
        }
    }
    

    然后您的 WebMethod 将更改为接受学生类对象列表,如下所示:

    [WebMethod]
    public static void SetStudentInfo(List<Student> Students)
    {
        foreach (Student s in Students)
        {
            //Do whatever here System.Console.WriteLine(s.name);
        }
    }
    

    那么您需要做的就是稍微改变您的 Ajax 调用,如下所示:

    function setStudentInfo() {
        var jsonObjects = [
            { id: 1, name: "mike" },
            { id: 2, name: "kile" },
            { id: 3, name: "brian" },
            { id: 1, name: "tom" }
        ];
    
        $.ajax({
            type: "POST",
            url: "ConfigureManager.aspx/SetStudentInfo",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            data: { Students: JSON.stringify(jsonObjects) },
            success: function (result) {
                alert('success');
            },
            error: function (result) {
                alert(result.responseText);
            }
    
        });
    }
    

    【讨论】:

      【解决方案4】:

      试试这个代码:

      function setStudentInfo() {
      
      var jsonObjects = {"students" : [
          { id: 1, name: "mike" },
          { id: 2, name: "kile" },
          { id: 3, name: "brian" },
          { id: 1, name: "tom" }
      ]};
      
      $.ajax({
          type: "POST",
          url: "ConfigureManager.aspx/SetStudentInfo",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          async: false,
          data: JSON.stringify(jsonObjects),
          success: function (result) {
              alert('success');
          },
          error: function (result) {
              alert(result.responseText);
          }
      
      });
      

      }

      【讨论】:

        【解决方案5】:

        您实际上并没有将 json 发送到服务器,发送 json 只需为 data 属性传递一个 json 字符串。

        data: JSON.stringify(jsonObjects),
        

        【讨论】:

        • 执行更改时,我得到以下信息" "{"Message":"Type \u0027System.Collections.Generic.IDictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]\u0027 不支持数组的反序列化。","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer序列化器, Boolean throwOnError, IList&convertList
        • @user829174 我对 asp.net 了解不多,但看起来您的 webmethod 需要一个对象并获取一个数组。
        • 感谢您的反馈,我应该如何更改我的方法的签名,以便能够将特定的 JSON 对象发送到服务器,您能分享代码吗?
        猜你喜欢
        • 1970-01-01
        • 2017-03-02
        • 1970-01-01
        • 1970-01-01
        • 2020-10-27
        • 1970-01-01
        • 2016-11-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多