1

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

i had the same issue by adding GigId: button.attr("data-gig-id"). able to fix it this might help

$(document).ready(function() { 
        $(".js-toggle-attendance").click(function (e) {
            var button = $(e.target);

            $.post("/api/attendances", { GigId: button.attr("data-gig-id") })
                .done(function() {
                    button
                        .removeClass("btn-default")
                        .addClass("btn-info")
                        .text("Going");
                })
                .fail(function() {
                    alert("something failed !");`enter code here`
                });
        });
    });

Comments

0

In case it helps someone else, I had a DTO without a parameter-less constructor and pre ASP.NET Core used to throw an exception on that, whereas ASP.NET Core doesn't, it just gives you a null object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.