【问题标题】:Array Parameter Empty for jQuery Ajax Call to MVCjQuery Ajax 调用 MVC 的数组参数为空
【发布时间】:2019-02-20 04:45:02
【问题描述】:

我有一个简单的 MVC api 方法:

[System.Web.Http.HttpPost]  // Important: it is not System.Web.Mvc.HttpPost
public void MyMethod(object[] arr)
{
    ...
}

我使用这个 javascript 调用它:

$.ajax({
    url: url,
    method: "POST",
    data: { arr: ['1','2']},
    dataType: "json",
    traditional: true,
    error: function (e) {
        ...
    },
    success: function (res) {
        ...
    }
});

调用成功但C#代码中arr的值为空数组(string[0])。我发现了多个此类调用的示例,主要建议添加传统的:true,但它仍然不起作用。我还尝试提供不同格式的数据,例如:

  • 数据:{ arr: ['1','2']}
  • 数据:{ ['1','2']}
  • 数据:['1','2']
  • JSON.stringify(['1', '2'])

这些都不起作用。想法?

【问题讨论】:

标签: c# jquery arrays asp.net-mvc asp.net-web-api


【解决方案1】:

需要指定[FromBody]参数:

[System.Web.Http.HttpPost]  // Important: it is not System.Web.Mvc.HttpPost
public void MyMethod([FromBody] object[] arr)
{
    ...
}

你的代码应该是:

$.ajax({
    url: url,
    method: "POST",
    data: ['1','2'],
    dataType: "json",
    traditional: true,
    error: function (e) {
        ...
    },
    success: function (res) {
        ...
    }
});

如果您指定一个键/值,例如{Arr: ['1', '2']},那么您应该为您的正文创建一个结构:

class MyMethodPostJson
{
    public List<string> Arr;
}

并使用:

[System.Web.Http.HttpPost]  // Important: it is not System.Web.Mvc.HttpPost
public void MyMethod([FromBody] MyMethodPostJson arr)
{
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    相关资源
    最近更新 更多