Haley Mueller
Haley Mueller

Reputation: 497

Model isn't binding when I send JSON to MVC controller

I might be overlooking something but my JSON payload isn't being binded at all for my controller. I have tried making a class where it has a List<Models.UpdateChatRequestModel> Chats but that hasn't worked for me either. I have tried using an array name but that hasn't seem to work either.

Controller:

[HttpPost]
public IActionResult UpdateChatRequest(IList<Models.UpdateChatRequestModel> request)
{
    var model = new Models.ChatModel();

    return Json(model);
}

Model:

public class UpdateChatRequestModel
{
    public int UserID
    {
        get; set;
    }

    public int LastID
    {
        get; set;
    }
}

JavaScript:

class Chat {
    constructor(UserID, LastID) {
        this.UserID = UserID;
        this.LastID = LastID;
    }
}
var chats = [new Chat(0, 1), new Chat(1, 4)];

function RequestChatUpdate() {
    $.ajax({
        type: "POST",
        url: '/Chat/UpdateChatRequest',
        data: JSON.stringify(chats),
        contentType: "application/json",
        success: function (data) {
            alert("got response from chat update");
        }
    });
}

JSON being sent from RequestChatUpdate():

[{"UserID":0,"LastID":1},{"UserID":1,"LastID":4}]

Upvotes: 1

Views: 850

Answers (2)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14218

You need to add the name for your JSON, Looks like this

var request = JSON.stringify({ 'request': chats });

Then your ajax request would become

function RequestChatUpdate() {
    $.ajax({
        type: "POST",
        url: '/Chat/UpdateChatRequest',
        data: request,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
            alert("got response from chat update");
        }
    });
}

Updated

According to this specs, it said that

In order to bind the JSON correctly in ASP.NET Core, you must modify your action to include the attribute [FromBody] on the parameter. This tells the framework to use the content-type header of the request to decide which of the configured IInputFormatters to use for model binding

So that's the reason why you need to add [FromBody]

Upvotes: -1

Haley Mueller
Haley Mueller

Reputation: 497

I have found the answer.

You have to have [FromBody] in front of the model parameter like so:

[HttpPost]
public IActionResult UpdateChatRequest([FromBody] IList<Models.UpdateChatRequestModel> request)
{
    var d = ModelState;
    var model = new Models.ChatModel();

    return Json(model);
}

Upvotes: 3

Related Questions