我正在努力将 json 数据从 ajax 请求发布到 asp mvc Controller 方法,但由于某些未知原因,asp mvc 模型绑定(bind)器没有绑定(bind)它。
我尝试遵循此处发布的多个答案,包括以下内容
Post json object to ASP MVC doesn't work properly
但是我的 jQuery ajax 方法总是将 null 值发送到 asp mvc Controller 。
基本上,我试图通过 ajax 请求加载部分 View 。
Ajax 请求
var myData =
{
"Id": 7,
"Name": "Name 1"
};
var obj = { 'test': myData };
var val = JSON.stringify(obj);
console.log(val);
$.ajax({
type: 'POST',
dataType: 'html',
url: '/Home/Partial',
contentType: 'application/json',
data: val,
success: function (xhr, status, response) {
console.log(response);
$('#1').html(response.responseText);
},
error: function (err) {
alert("error - " + err);
}
});
Controller 方法
[HttpPost]
public IActionResult Partial(Test test)
{
return PartialView("_Test", test);
}
型号
public class Test
{
public int Id;
public string Name;
}
最佳答案
myData
足以绑定(bind)对象。
var myData = { Id: 7, Name: "Name 1" };
var val = JSON.stringify(myData);
console.log(val);
$.ajax({
type: 'POST',
dataType: 'html',
url: '/Home/Partial',
contentType: 'application/json',
data: val,
success: function (xhr, status, response) {
console.log(response);
$('#1').html(response.responseText);
},
error: function (err) {
alert("error - " + err);
}
});
您还应该考虑参数上的 [FromBody]
属性,以便模型绑定(bind)器知道检查模型的主体。
[HttpPost]
public IActionResult Partial([FromBody]Test test) {
return PartialView("_Test", test);
}
关于jquery - 使用 asp.net core 和 Jquery 从 ajax 请求将对象绑定(bind)到 asp mvc Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45331925/