The model fails to bind when JSON is sent to the MVC controller

I've been facing an issue with my JSON payload not getting binded in my controller. I attempted creating a class with

List<Models.UpdateChatRequestModel> Chats
, but that didn't work for me. I also tried using an array name, but that approach seemed to fail as well.

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 sent from RequestChatUpdate():

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

Answer №1

I've come across the solution.

To successfully update the chat request, make sure to include [FromBody] before the model parameter in the following manner:

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

    return Json(model);
}

Answer №2

To properly structure your JSON, you must include the name as shown below:

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

Once this is done, your ajax request should look like this:

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

As per this resource, it is mentioned that

To bind JSON correctly in ASP.NET Core, you need to use the [FromBody] attribute on your action parameter. This instructs the framework to utilize the content-type header of the request for determining which IInputFormatters to use for model binding.

This is why adding [FromBody] is necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Swap out the image backdrop by utilizing the forward and backward buttons

I am currently working on developing a Character Selection feature for Airconsole. I had the idea of implementing this using a Jquery method similar to a Gallery. In order to achieve this, I require a previous button, a next button, and the character disp ...

Exploring JSON array handling with jquery

Here is the JSON data I am working with: { "category": { "category_identification": "1", "category_name": "C1", "image_one": "1.PNG", "image_two": "1_.PNG", "logo": "LOGO_1.PNG", "category_description": "DESCRIPTION" }, "responseCo ...

tips for repurposing a jquery function

Similar Question: JQuery: Issue with $(window).resize() not triggering on page load In my jQuery code snippet below, I am trying to make a function work both on window resize and page load without duplicating the code. The current implementation works ...

Unfamiliar String Conversion to JSON in Java

Need assistance with parsing a JSON-formatted string obtained from a URL. The field and size of the data may vary, making it difficult to iterate over the structure of the JSON object. Here is an example of the string: {"_index":"my_index","_type":"my_t ...

improve your AJAX implementation in Django

Recently, I implemented some AJAX functionality in a Django application that I have been developing. Coming from a background in Ruby on Rails, I haven't had much experience with pure JavaScript. So, inspired by Rails' partials, I came up with ...

Using ASHX to Return JSON in ASP.NET

I have implemented autocomplete functionality on my website. The JavaScript part is complete and I am able to retrieve the MembershipUser object of the matching user. Now, I need to format the JSON response as follows: { query:'Li', suggestio ...

Incorporating an external SVG link into a React application

While I may not be an SVG expert, I haven't encountered any issues with loading SVGs in my React app so far. I prefer using the svg tag over the image tag because sizing tends to present problems with the latter option when working with external links ...

Failed to convert the value "hello" to an ObjectId (string type) for the _id path in the product model

i am currently using node, express, and mongoose with a local mongodb database. all of my routes are functioning correctly except for the last one /hello, which is giving me this error: { "stringValue": "\"hello\"&qu ...

Storing keys and multiple maps with React applications

Having a multiple array with an option set created, everything is functioning correctly const groups1 = OrgServices.reduce((all, cur) => ((all[cur.grouptype] ??= []).push(...cur.servicetype), all), {}); const output1 = Object.entries(groups1).map ...

Utilizing a MongoDB aggregation pipeline with C# programming

I've successfully executed an eight-step 'aggregation query' in MongoDB using the console and RoboMongo. db.getCollection("...").aggregate([ {$match: { ... } }, {$unwind: ... }, {$project: { ... } }, {$group: { ... } }, ...

Convert JavaScript code to Google Appscript

Looking for guidance on incorporating Javascript code into my Google Appscript. Here is the code snippet: I have a separate Stylesheet.html file saved. Can someone advise me on how to invoke the functions within the html file? <script> //google. ...

Distinguishing between newtonsoft.json and microsoft.aspnetcore.mvc.newtonsoft.json - what sets them apart?

Can you explain the distinctions between these two libraries? https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.NewtonsoftJson/ vs https://www.nuget.org/packages/Newtonsoft.Json/ ...

Dynamically load select options using Ajax

I'm a newcomer to javascript and ajax, and I'm working on implementing Ajax to display the current category on my HTML select in a CodeIgniter project. Below is the code snippet: HTML: <select class="form-control" name="category" id="categor ...

Creating a read-only DIV using Angular - a step-by-step guide

Is there a simple way to make all clickable elements inside a div read only? For example, in the provided HTML code, these divs act like buttons and I want to disable them from being clicked. Any tips or shortcuts to achieve this? Thank you. #html < ...

When trying to upload a file using multer, an error occurred stating "Unexpected field

My current issue involves using multer to upload an image from a form. However, I am encountering an Unexpected field error after uploading the image. In my HTML code, I have specified the file and file-model names as myFile. app.js var express = re ...

Enhancing Highcharts bar chart tool tip to display dynamic data

I am currently utilizing highcharts.js for my project. The goal is to customize the tooltip. I have created a Java method that returns output in JSON format like this: syList: [{ "value1": "Some Area", "value2": "1", "agrAcronym": "AB ...

Trouble accessing nested components in Angular CLI beyond the first level of components

I'm diving into Angular CLI for the first time and trying to recreate a previous web project of mine. I've managed to nest and display components inside the root component successfully, but after that, I'm facing issues referencing any compo ...

Navigating through the world of WebSQL data entry

I've encountered a challenge while utilizing WebSQL for my Chrome Extension. This is my first experience with it, so I decided to refer to this tutorial and modify it to suit my requirements: http://www.html5rocks.com/en/tutorials/webdatabase/todo/ B ...

A guide on triggering a function when a button is clicked in reactjs

Can anyone please help me with this issue I'm having: how do I execute a function when a button is clicked? I currently have the following code but it's not working export var Modulo = React.createClass({ prom1: function () { retur ...

Start the Express server by utilizing Grunt

Can anyone assist me with adding a task to my Gruntfile that will start my Express server instead of the default one? I attempted to create a task and use require("server.js"), but it doesn't seem to be working properly. When I run "grunt mytask", the ...