如何在從數據字段傳遞數據時使用Ajax POST數據?問題似乎是因爲我的數據沒有正確發佈到控制器,因爲我試圖用硬編碼的數字替換實際的數據屬性,並且仍然無法POST該數字。這裏是我的Ajax調用:ASP.NET Core 1中的Ajax數據發佈不會傳遞值
$(".js-toggle-attendance")
.click(function(e) {
var button = $(e.target);
$.ajax({
url: "/api/attendances/",
method: "POST",
contentType: "application/json",
data: 'gigId : button.attr("data-gig-id")',
dataType: "json"
})
.done(function() {
button
.removeClass("btn-default")
.addClass("btn-info")
.text("Going");
})
.fail(function() {
alert("Something failed!");
});
});
});
</script>
我的控制器操作如下:
[HttpPost]
public IActionResult Attend(AttendanceDTO dto)
{
和AttendanceDTO只是一個簡單的數據傳輸對象類:
public class AttendanceDTO
{
public int GigId { get; set; }
}
我曾嘗試以下數據方法的變體,以及Chrome開發工具/網絡請求有效負載中的內容如下(我點擊ID = 1的按鈕):
data: 'gigId : button.attr("data-gig-id")'--> gigId : button.attr("data-gig-id")
data: { "gigId": button.attr("data-gig-id") } --> gigId=1
data: button.attr("data-gig-id") --> 1 No Properties
data: "2" --> 2 No Properties
在所有情況下,調試控制器動作顯示DTO場爲0
UPDATE: 我加入了[FromBody]標籤和JSON字符串化的數據,正確的數據似乎被髮布現在。但是,上面的失敗方法一直在執行。我更新的代碼拉如下錯誤信息:
$(".js-toggle-attendance")
.click(function(e) {
var button = $(e.target);
$.ajax({
url: "/api/attendances/",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ "gigId": button.attr("data-gig-id") }),
dataType: "json",
success: function() {
button
.removeClass("btn-default")
.addClass("btn-info")
.text("Going");
},
error: function(error) {
var x = error;
alert("Something failed!");
}
});
});
而且,我是能夠從Chrome瀏覽器開發工具來捕獲錯誤消息:
error = Object {readyState: 4, responseText: "", status: 200, statusText: "OK"
UPDATE上面FIX問題: 只需要刪除dataType:「json」,因爲服務器沒有推回json。