[英]AJAX post data is null in controller mvc
我嘗試將JSON對象發送回服務器。 這是我的AJAX電話:
$.ajax({
url: '/Home/NewService',
async: false,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCES");
}
});
瀏覽器調試器中對JSON.stringify(props)
的評估是
"[{"name":"firstName","value":"firstValue"}]"
這是被調用的控制器中的方法:
[HttpPost]
public void NewService(dynamic json)
{
Response.Write(json);
}
我遇到的問題是,上面的json
變量總是一個空對象。 success
函數被調用,但是當我調試時, json
var顯示為空。
請告訴我我做錯了什么。 謝謝。
我認為你不能像你想要的那樣綁定到動態類型。 您可以嘗試創建一個映射數據的類,例如:
public class Content
{
public string Name { get; set; }
public string Value { get; set; }
}
現在你的行動:
[HttpPost]
public ActionResult NewService(Content[] data)
{
// sweet !
}
在你的js像Olaf Dietsche說你需要指定你的contentType
:
var props = [
{ "Name": "firstName", "Value": "firstValue" },
{ "Name": "secondName", "Value": "secondValue" }
];
$.ajax({
url: '/Home/NewService',
contentType: "application/json",
async: true,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS!");
}
});
根據jQuery.ajax()
,默認內容類型是application/x-www-form-urlencoded
。 如果要將數據作為JSON發送,則必須將其更改為
$.ajax({
url: '/Home/NewService',
contentType: 'application/json',
...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.