【问题标题】:Why does $post not work but $ajax works on the asp.net web api controller?为什么 $post 不起作用但 $ajax 在 asp.net web api 控制器上起作用?
【发布时间】:2019-03-26 08:50:16
【问题描述】:

我想知道为什么 $.ajax() 请求有效,但 $.post() 在控制器上只返回一个空数组。

控制器

[Route("api/actuary/{actuaryId:long}/documents/")]
[HttpPost]
public async Task<IHttpActionResult> uploadCourseTrainingProofAsync(List<CourseModel> courseAttended)
{
    //code .....
}

此请求有效

$.ajax({
    url: url,
    cache: false,
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(courseAttended),
    dataType: "json",
    success: function (data) {
        console.log(data)
    }
})

但是这个不行,控制器的 courseAttended 数组是空的。

$.post(url, JSON.stringify(courseAttended), function (response) {
    console.log(response)
},"json")

【问题讨论】:

  • 您是否尝试在浏览器的开发者工具网络面板中查看差异?
  • 您是否在控制台中遇到任何错误以及为什么在函数调用结束时传递“json”?我认为不需要

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


【解决方案1】:

$.post() 使用默认的 contentType: 'application/x-www-form-urlencoded; charset=UTF-8',但您在 $.ajax() 方法中使用带有字符串化数据的 contentType: 'application/json; charset=utf-8',

如果您要使用 $.post(),则需要使用集合索引器生成数据以匹配您的 List&lt;CourseModel&gt; 参数,例如

var data =  { [0].SomeProperty: SomeValue, [0].AnotherProperty: AnotherValue, [1].SomeProperty: SomeValue, .... };
$.post(url, data , function (response) {
    ....
});

【讨论】:

    【解决方案2】:

    您不必在 $.post 中对对象进行字符串化

     $.post(url, courseAttended, function (response) {
            console.log(response)
        },"json")
    

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 1970-01-01
      • 2015-08-10
      • 2012-09-15
      • 2023-04-09
      • 1970-01-01
      • 2023-03-18
      • 2021-02-10
      • 2020-03-30
      相关资源
      最近更新 更多