【问题标题】:Posting list of objects to web api method将对象列表发布到 Web api 方法
【发布时间】:2015-05-16 01:48:00
【问题描述】:

您好,我正在尝试以这种方式将对象列表发布到 Web api 方法:

var uri = "http://localhost:" + port + "/api/Account";
$.ajax({
    dateType: "json",       
    method: "POST",
    url: uri,
    data: JSON.stringify(schedule),
    success: function (result) {
        alert(result);
    },
    error: function () {
        alert("mal")
    }
})

我的web api方法如下:

public IHttpActionResult createSchedule([FromBody]List<Schedule> schedule)
{
        return Ok(schedule.Capacity);
}

问题是返回 0 而不是列表中对象的数量。我认为那是因为列表是空的。我在做什么坏事?我读了一些关于将数据设置为date: {"": schedule} 的内容,但它没有用。它抛出了一个空引用异常。

【问题讨论】:

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


    【解决方案1】:

    您正确地传递了数据,但您需要指出请求的内容类型是 JSON($.ajax 中的 dataType 选项告诉 jQuery 对 响应的期望)。将contentType 参数添加到ajax 调用中,它应该可以工作:

    var uri = "http://localhost:" + port + "/api/Account";
    var schedule = [{}, {}, {}];
    $.ajax({
        dateType: "json",
        contentType: "application/json",
        method: "POST",
        url: uri,
        data: JSON.stringify(schedule),
        success: function (result) {
            alert(result);
        },
        error: function () {
            alert("mal")
        }
    })
    

    【讨论】:

      【解决方案2】:

      webapi 方法将寻找 schedule 对象

      所以将你的 data: schedule, 更改为 data: { schedule: schedule },

      【讨论】:

      • 这不是问题,因为该方法运行良好。否则它将无法正常工作。无论如何,我刚刚尝试过,它仍然返回 0。
      • hmm.. 是schedule 看起来像[{ },{ }..]
      • 是的,看起来像你说的。
      【解决方案3】:

      我认为错误在于 web api 方法,因为我正在使用邮递员 (chrome) 进行测试,并且在尝试发送此 json 时出现空引用异常:

      var schedule = [{day: "Lunes", hour: "9-11", id_flat: 1},{day: "Martes", hour: "15-16", id_flat: 1}]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-15
        • 2016-05-27
        • 1970-01-01
        相关资源
        最近更新 更多