gpt4 book ai didi

asp.net - 使用 jQuery 和 ajax 将整数列表传递给 WebMethod

转载 作者:行者123 更新时间:2023-12-01 02:25:25 25 4
gpt4 key购买 nike

我正在开发一个网页(ASP.NET 4.0),并且刚刚开始简单地尝试让这个 ajax 调用正常工作(我是 ajax/jQuery 新手),但我在调用时遇到错误。这是js:

    var TestParams = new Object;
TestParams.Items = new Object;
TestParams.Items[0] = 1;
TestParams.Items[1] = 5;
TestParams.Items[2] = 10;

var finalObj = JSON.stringify(TestParams);

var _url = 'AdvancedSearch.aspx/TestMethod';

$(document).ready(function ()
{
$.ajax({
type: "POST",
url: _url,
data: finalObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
$(".main").html(msg.d);
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(thrownError.toString());
}
});

这是我的代码隐藏文件中的方法:

[Serializable]
public class TestParams
{
public List<int> Items { get; set; }
}

public partial class Search : Page
{
[WebMethod]
public static string TestMethod(TestParams testParams)
{
// I never hit a breakpoint in here
// do some stuff
// return some stuff
return "";
}
}

这是我发回的字符串化 json:

{"Items":{"0":1,"1":5,"2":10}}

当我运行它时,我收到此错误:

Microsoft JScript runtime error: 'undefined' is null or not an object

它在错误函数上中断。

我还尝试了使用此最终 json 构建 json 的变体(基于网站上的示例):

    var TestParams = new Object;
TestParams.Positions = new Object;
TestParams.Positions[0] = 1;
TestParams.Positions[1] = 5;
TestParams.Positions[2] = 10;

var DTO = new Object;
DTO.positions = TestParams;

var finalObj = JSON.stringify(DTO)

{"positions":{"Positions":{"0":1,"1":5,"2":10}}}

同样的错误消息。

将网页中的整数列表发送到我的 webmethod 似乎并不困难。有什么想法吗?

谢谢,周杰伦

最佳答案

我尝试过这个,它可以在 .NET 3.5 中运行。不同之处在于序列化后的数组就像 Items:[1,2]在 .aspx 中

var _url = 'Default.aspx/TestMethod';
$(document).ready(
function() {
$.ajax(
{
type: "POST",
url: _url,
data: '{"i":{"Items":[1,2]} }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$(".main").html(msg.d);
},
error: function(xhr, ajaxOptions, thrownError) {
debugger;
alert(thrownError.toString());
}
}
)
}
);

在 .cs 中

[WebMethod]     
public static string TestMethod(TestParams i)
{


return "whaever";
}

我从中得到了字符串

var serializer = new JavaScriptSerializer();

var param = new TestParams();
var list = new List<int> {1, 2};

param.Items = list;

string serializedString = serializer.Serialize(param);

希望这有帮助。

关于asp.net - 使用 jQuery 和 ajax 将整数列表传递给 WebMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4523769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com