Reza Reza - 4 months ago 8
Ajax Question

Ajax data post in ASP.NET Core 1 doesn't pass values

How do I POST data using Ajax when passing data from data field? The issue seems to be that my data doesn't get posted to the controller correctly because I have tried to replace the actual data-attribute with hard-coded numbers and still cant POST that number. Here is my ajax call:

$(".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>


my controller action is as follows:

[HttpPost]
public IActionResult Attend(AttendanceDTO dto)
{


and the AttendanceDTO is just a simple Data transfer object class:

public class AttendanceDTO
{
public int GigId { get; set; }
}


I have tried the following variants for the data method, and what is in Chrome Dev Tools/Network Request payload is as follows (I am clicking button with 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


In all cases, debugging the controller actions shows the dto field as 0.

UPDATE:
I added the [FromBody] tag and JSON stringified the data, and the correct data seems to be posting now. However, the fail method above keeps executing all the time. I updated the code to pull the error message as below:

$(".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!");
}
});
});


And the error message that I Was able to capture from Chrome Dev Tools:

error = Object {readyState: 4, responseText: "", status: 200, statusText: "OK"


UPDATE TO FIX ISSUE ABOVE:
Just had to remove dataType: "json" because server was not pushing back json.

Answer

You did not declare your action parameter as [FromBody].

[HttpPost]
public IActionResult Attend([FromBody]AttendanceDTO dto)
{
}

should do the trick. As for the data, the { "gigId": button.attr("data-gig-id") } should be the right format, though you may need to convert it to json string before passing it.