![](/img/trans.png)
[英]NULL values while passing JSON data to controller via AJAX
[英]AJAX Passing JSON to Controller as String Returns Null
我有以下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();
}
但是,控制器接收的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" })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.