c# - 对 ASP.NET Web 服务的 AJAX 请求 - 使用什么参数类型?

标签 c# jquery asp.net ajax json

我有一个 JSON 对象数组,其中一些包含键/值对,其值是一个数组。

例子:

var jsonArray = [{ "key1":"value1", "key2":["value21", "value22"]},
                 { "key1":"value3", "key2":["value41", "value42"]}];

编辑:不小心使用了大括号而不是方括号。

我正在尝试使用 jQuery 通过 AJAX 将其发送到 ASP.NET Web 服务:

$.ajax({
    type: "post",
    url: "example.asmx/SomeFunction"
    data: "{ 'items': '" + JSON.stringify(jsonArray) + "' }",
    contentType: "application/json;charset=utf-8",
    dataType: "json"
});

这是发送数据的正确方法吗?另外,SomeFunction 参数中我需要什么数据类型来接受和解析 JSON 数据?

最佳答案

Is this the correct way to send the data?

不,下面会更好:

$.ajax({
    type: "post",
    url: "example.asmx/SomeFunction"
    data: JSON.stringify({ items: jsonArray }),
    contentType: "application/json;charset=utf-8",
    dataType: "json"
});

Also, what data type do I need in the SomeFunction parameter to accept and parse the JSON data?

它将映射到:

public void SomeFunction(IEnumerable<Foo> items)
{
    ...
}

哪里Foo定义如下:

public class Foo
{
    public string Key1 { get; set; }
    public IEnumerable<string> Key2 { get; set; }
}

在我的示例中,我使用了 IEnumerable<T>正如我假设您只会枚举这些值,但如果您需要索引器,您也可以将它们定义为数组 T[] .

关于c# - 对 ASP.NET Web 服务的 AJAX 请求 - 使用什么参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5174492/

相关文章:

c# - 如何在忽略大小写的情况下检查枚举值中的 "Contains"C#?

c# - 使用 EPPlus C# 在单个 excel 单元格中提供不同的样式

javascript - 列出/输出来自单个输入的逗号分隔值

jquery - Bootstrap 模式数据关闭关闭模式时不关闭 mozilla 和 IE 中的音频

javascript - 我无法访问 <asp :textbox> value in code behind file

asp.net - VS2010本地资源后缀问题

asp.net - 如何在32位模式下运行VS 2010本地IIS

c# - 如何访问 GroupBy 返回的内容

c# - 我需要在项目中获取文件夹路径

asp.net-mvc - jQuery:为什么 $.post 执行 GET 而不是 POST