【发布时间】: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