【问题标题】:Send JSON object to MVC 6 WebApi controller using jQuery使用 jQuery 将 JSON 对象发送到 MVC 6 WebApi 控制器
【发布时间】:2015-08-25 08:31:26
【问题描述】:

我无法将 JSON 对象发送到我的 MVC 6 WebApi 控制器。

当我在 fiddler 中查看 RAW 数据时,我当前发送的内容是这样的:

Username=brugernavn&Password=adgangskode&DocumentId=document.dotx

我认为我的控制器期望收到的是:

{"Username":"brugernavn","Password":"adgangskode","DocumentId":"document.dotx"}

我的控制器代码:

namespace DemoApp.Controllers
{
    [Route("api/[controller]")]
    public class DocumentController : Controller
    {

        // POST: api/documentcontroller/GetDocumentInformation
        [HttpPost]
        [Route("[action]")]
        public string GetDocumentInformation([FromBody] GetDocumentInformationRequest documentInformationRequest)
        if (documentInformationRequest == null)
        {
            return "null";
        } else {
            return "ok";
        }
    }
}

我的 GetDocumentInformationRequest 模型类:

public class GetDocumentInformationRequest
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string DocumentId { get; set; }
}

我的 jQuery 代码:

var source = {
    'Username': 'brugernavn',
    'Password': 'adgangskode',
    'DocumentId': documentID
}
var apiUrl = location.origin + "/api/documentcontroller/GetDocumentInformation";
$.ajax({
    type: "POST",
    dataType: "json",
    url: apiUrl,
    data: source,
    success: function (data) {
        alert(data);
    },
    error: function (error) {
        var x = error; //break here for debugging.
    }
});

ajax 请求确实命中了控制器,但 documentInformationRequest 参数为空。

此外,ajax 请求每次都会在错误块中结束,但那是因为控制器当前只返回“null”,这不是有效的 JSON... (它确实返回了一个代码 200,并且没有抛出任何错误。)

我尝试了许多 ajax 请求的变体,但到目前为止,没有一个可以正确地将 JSON 对象发送到控制器。

【问题讨论】:

    标签: jquery json asp.net-web-api asp.net-core-mvc


    【解决方案1】:

    你只需要使用 JSON.stringify

    $.ajax({
       type: "POST",
       dataType: "json",
       url: apiUrl,
       data: JSON.stringify(source),
       success: function (data) {
           alert(data);
       },
       error: function (error) {
           var x = error; //break here for debugging.
       }
    });
    

    【讨论】:

      【解决方案2】:

      感谢维塔利的回答。 与此同时,我确实偶然发现了一个类似的解决方案,尽管在控制器接受数据之前我还需要添加 contentType 参数。

      所以就我而言,完整的答案如下:

      $.ajax({
          type: "POST",
          dataType: "json",
          url: apiUrl,
          data: JSON.stringify(source),
          contentType: "application/json",
          success: function (data) {
              alert(data);
          },
          error: function (error) {
              var x = error; //break here for debugging.
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-29
        • 1970-01-01
        • 2014-03-01
        • 1970-01-01
        • 2014-10-20
        • 2014-10-31
        相关资源
        最近更新 更多