如何使用 Ajax 和 ASP.NET WebMethod 传递 JSON 对象

2024-01-06

我在使用 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深度限制,JavaScriptSerializer序列化器) 在System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer序列化器,字符串输入,类型类型,Int32深度限制) 在 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](字符串输入) 在 System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext 上下文,JavaScriptSerializer 序列化器) 在 System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData,HttpContext 上下文) 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}"


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

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

});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Ajax 和 ASP.NET WebMethod 传递 JSON 对象 的相关文章

随机推荐