我有以下 AJAX 调用,经过简化以尝试查明问题:
$('#userUpdateForm').submit(function (e) {
$.ajax({
type: "POST",
url: '@Url.Action("submitForm", "Home")',
data: JSON.stringify({
'blue': window.glbBlue,
'eg2': 'eg3'
}),
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("Success");
},
error: function (result) {
alert("A problem occured when submitting the form.");
}
});
e.preventDefault();
});
这会调用以下方法:
[HttpPost]
public ActionResult submitForm(string json)
{
System.Diagnostics.Debug.WriteLine("made it here");
var check = System.Web.Helpers.Json.Decode(json);
System.Diagnostics.Debug.WriteLine(check);
System.Diagnostics.Debug.WriteLine(check.glbBlue);
return View();
}
但是, Controller 收到的 JSON 为空。为什么会出现这种情况?我可以在浏览器中看到有一个请求负载,其中包含我期望的值。 “Window.glbBlue”是一个全局值,我也知道它已正确设置,因为警报用于检查其值。
最佳答案
您发送数据
data: JSON.stringify({
'blue': window.glbBlue,
'eg2': 'eg3'
})
表示您的操作收到两个参数 blue
和 eg2
,但您只收到一个未提供的参数 json
。因此,json
为 null
。
您可以将 public ActionResult SubmitForm(string json) {}
更改为 public ActionResult SubmitForm(string blue,string eg2) {}
。
或者
数据:JSON.stringify({json: "something"})
关于javascript - AJAX 将 JSON 作为字符串传递给 Controller 返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43920377/