【问题标题】:$.Ajax post array to Web Api 2 not working for me$.Ajax 将数组发布到 Web Api 2 对我不起作用
【发布时间】:2015-10-23 23:23:32
【问题描述】:

数据模型

public class Foo
{
    public string Id { get; set; }
    public string Title { get; set; }
}

Web API 2 控制器

[Route("api/UpdateFoo")]
public IHttpActionResult UpdateFoo(List<Foo> Foos)
{

}

JS

// here I need to create fooData which is list of foo


var fooData = [];
fooData.push({ Title: "title1" });
fooData.push({ Title: "title2" });

$.ajax({
    method: "POST",
    url: "api/UpdateFoo",
    data: fooData
    }).done(function (result) {
        // good
    }).fail(function(xhr) {
        alert(xhr.responseText);
    });

我在这里缺少什么?在提琴手看起来我已经正确发送了 fooData 但是它没有在 Web Api 控制器中收到,我能够输入带有断点的方法但是空列表中的值

【问题讨论】:

    标签: jquery ajax asp.net-web-api


    【解决方案1】:

    我昨天刚刚在这上面花了几个小时。通过 ajax See Quirk Here 发布数据时,asp.net webApi 中有一个已知的“怪癖”。总结一下您的特定问题,只需添加以下内容:

    var fooData = [];
    fooData.push({ Title: "title1" });
    fooData.push({ Title: "title2" });
    
    $.ajax({
        method: "POST",
        url: "api/UpdateFoo",
        data: {'': fooData} //<-- the '' empty prefix name for the data
        }).done(function (result) {
            // good
        }).fail(function(xhr) {
            alert(xhr.responseText);
        });
    

    【讨论】:

    • 非常感谢,donB!有用。顺便问一下,你知道如何让它在 VB.net 中工作吗?我将代码转换为VB,列表显示正确的记录#,但内容为空。
    • @user1617676 很抱歉回复得太晚了。我已经好几次没玩过VB了。你有一些代码要看吗?
    【解决方案2】:

    创建另一个模型以包含列表

    public class ListOfFoos
    {
        public List<Foo> Foos {get; set;}
    
        public ListOfFoos()
        {
            Foos = new List<Foo>();
        }
    }
    

    那么你的控制器应该是这样的:

    [Route("api/UpdateFoo")]
    public IHttpActionResult UpdateFoo(ListOfFoos listOfFoos)
    {
    
    }
    

    现在如果你像这样传入 JSON,你应该能够在控制器中获取列表:

    {
      "foos" : [
        { "Id": 1, "Title" : "f1" }, 
        { "Id": 2, "Title" : "f2" }
      ]
    }
    

    【讨论】:

      【解决方案3】:

      尝试进行 Ajax 调用:

      $.ajax({
          method: "POST",
          url: "api/UpdateFoo",
          data: JSON.stringify(fooData),
          contentType: 'application/json'
          }).done(function (result) {
              // good
          }).fail(function(xhr) {
              alert(xhr.responseText);
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-01
        • 1970-01-01
        • 2015-03-22
        • 1970-01-01
        • 2016-11-06
        相关资源
        最近更新 更多