【问题标题】:Bind model from jQuery ajax call in webApi controller从 webApi 控制器中的 jQuery ajax 调用绑定模型
【发布时间】:2018-01-09 11:39:36
【问题描述】:

我无法使用 jQuery 将数据对象发送到 webApi 控制器。调用到达响应的方法,但 MyMethod 中的 textValue 和 FunValues 对象为空。我已经尝试不使用 [FromBody],也尝试使用称为 textValue 的简单字符串值。结果是“SUCESS: your string is”,没有发送字符串。

这是我的 jQuery

  $.ajax({

            url: "api/ApiTest/MyMethod",
            method: "POST",
            data: {

                textValue: "This is text"

            },
            success: function (result) {
                console.log("SUCESS: " + result);
            },
            error: function (data) {
                console.log("error: " + data.responseText);
            }
        });

这是apiController中的方法和类

  [HttpPost]
    public string MyMethod([FromBody] FunValues values)
    {
        return "your string is " + values.textValue;
    }

    public class FunValues
    {
        public string textValue; 

    }

【问题讨论】:

  • 我的问题是如何将 Ajax 调用中的数据绑定到控制器中的参数或对象。不是如何返回数据。
  • 没有。调试时jquery发送的数据在方法中为null。
  • 道歉。误读您的问题
  • 没问题。还是谢谢。
  • 您可能想使用 fiddler 并检查 jquery 传递的内容类型。

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


【解决方案1】:

可能 $.ajax 现在用的不多。因此,很难创建应用程序并进行试用。由于 $.ajax 更多地用于表单时代,因此它具有一些不同的默认属性。

  1. $.ajax 使用 Content-Type: application/x-www-form-urlencoded;所以你需要将它显式设置为 application.json
  2. 您需要显式使用 JSON.stringify,否则它会像表单数据一样发送。

以下代码对我有用。

 $.ajax({
            url: "http://localhost:49946/api/Values/MyMethod",
            method: "POST",
            contentType: "application/json",
            data: JSON.stringify(
                {
                textValue: "This is text"
            }
            ),
            success: function (result) {
                console.log("SUCESS: " + result);
            },
            error: function (data) {
                console.log("error: " + data.responseText);
            }
        });

【讨论】:

    猜你喜欢
    • 2017-01-04
    • 2019-03-24
    • 2023-03-30
    • 2014-01-21
    • 1970-01-01
    • 2013-06-03
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多