【问题标题】:Object is null when passing from AJAX to Controller从 AJAX 传递到控制器时对象为空
【发布时间】:2020-11-29 23:21:49
【问题描述】:

我四处寻找答案,但没有任何帮助。

当从ajax请求传递一个对象模型绑定器不会将它绑定到模型,参数为null。

AJAX 请求:

function deleteImage(data) {
var s = $('#userServicesDropDownAuth :selected').text()
var i = String(data)
var input = {
    service: s,
    imgId: i
};
input = JSON.stringify({'input': input });
$.ajax({
    type: "POST",
    url: '/Actions/RemoveImage',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: input,
    success: function (data) {
        //switch pictures
        //or remove current, and replance with new.
    },
    error: function () {

    }
});

}

控制器:

  [HttpPost]
    public string RemoveImage([FromBody]UserWithImageModel input)
    {
         Service service = EnumParser.Parse(input.service);
        //var sessionId = SessionManager.GetCookieSession(service);
        //var bot = Factory.GetBot(service);
        //bot.RemoveImage(sessionId, imgId);


        return null;
    }

对象类:

 public class UserWithImageModel
{
    public string service { get; set; }
    public string imgId { get; set; }
}

当像这样发送 AJAX 数据时(在数据前添加名称,data: JSON.stringify({'input': input })):

function deleteImage(data) {
var s = $('#userServicesDropDownAuth :selected').text()
var i = String(data)
var input = {
    service: s,
    imgId: i
};

$.ajax({
    type: "POST",
    url: '/Actions/RemoveImage',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: JSON.stringify({'input': input }),
    success: function (data) {
        //switch pictures
        //or remove current, and replance with new.
    },
    error: function () {

    }
});

}

【问题讨论】:

  • 使用 [FromBody] 告诉 binder 在哪里寻找要绑定的数据 public string RemoveImage([FromBody]UserWithImageModel input)
  • 数据没有以正确的格式发送。将 input = JSON.stringify({'input': input }); 更改为 input = JSON.stringify(input);
  • 我测试了 [FormBody] 和两者,input = JSON.stringify({'input': input });只需输入 = JSON.stringify(input);还是什么都没有
  • 使用标签导致传递的变量只是空值,甚至属性都不是空值,只是对象本身
  • 对不起,你是对的,[FormBody] 确实解决了这个问题,第一次尝试时不知道出了什么问题,写下答案让我批准!谢谢。

标签: ajax asp.net-mvc asp.net-core


【解决方案1】:

我发现两个潜在问题

  1. 变量i 未在您的调用代码中分配。
  2. 控制器操作缺少[HttpPost] 属性

一些调试技巧: 在调用代码中设置断点时(在浏览器中使用 F12),变量input 是否被赋值?

您是否在浏览器中看到正在发出的请求,如果有,请检查参数值。

【讨论】:

  • 不知道为什么 i 变量消失了,我和他一起编辑,也测试了仍然为空,我添加了更多图片来解释并更好地展示它
【解决方案2】:

使用[FromBody] 明确告诉模型绑定器在哪里寻找要绑定的数据

public string RemoveImage([FromBody]UserWithImageModel input)

而且数据没有以正确的格式发送。

改变

input = JSON.stringify({'input': input }); 

只是

input = JSON.stringify(input);

参考Model Binding in ASP.NET Core

【讨论】:

    猜你喜欢
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2011-05-06
    相关资源
    最近更新 更多