ChasetopherB
ChasetopherB

Reputation: 464

Ajax call doesn't pass object to controller

I am trying to pass a string to an IActionResult function in an asp.net core 3.1 controller.

Ajax:

function CreateApprover() {
    const input = {
        PlantId: $('#ddlPlant').val(),
        UserId: $('#ddlUser').val(),
        CategoryId: $('#ddlCategory').val()
    };

    let jsonData = JSON.stringify(input);
    console.log(jsonData);

    $.ajax({
        contentType: "application/json",
        data: jsonData,
        traditional: true,
        method: "POST",
        url: "@Model.CreateUrl",
        success: function (data, textStatus, jqXHR) {                
            dialogDiv.dialog('close');                
        },
        error: function (xhr, err) {
            console.log(arguments);
            console.log('Request Status:');
            console.log(xhr.status);
            console.log('Status Text:');
            console.log(xhr.status);
            console.log(xhr.responseText);
        }
    });
}

Network Info:

enter image description here

enter image description here

C#:

    [HttpPost]
    public IActionResult CreateApprover(IFormCollection keyValues, [FromBody]ApproversCreateModel input)
    {
        return Ok();
    }

    public class ApproversCreateModel
    {
        public int UserId { get; set; }
        public int PlantId { get; set; }
        public int CategoryId { get; set; }
    }

The payload looks correct, and breakpoints are hit in the controller method, but the input param is always null, and the keyValues parameter has no data. What am I missing?

Upvotes: 0

Views: 1070

Answers (1)

ChasetopherB
ChasetopherB

Reputation: 464

Answered by Bryan Dellinger,

maybe try PlantId: parseInt($('#ddlPlant').val()), etc.

Upvotes: 1

Related Questions