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

How do you send a variable in a GET request with React?

My challenge is to retrieve data from a table where the teacherId matches the teacherId of the user who logs in, but I am facing difficulties in passing this teacherId from the front-end to the back-end. Below is the backend code: app.get("/api/get&q ...

Angular Redirect Function: An Overview

In the Angular project I'm working on, there is a function that should navigate to the home when executed. Within this function, there is a condition where if true, it should redirect somewhere. if (condition) { location.url('/home') ...

ng-repeat not functioning properly with FileReader

Here is a look at how my view appears: <body ng-controller="AdminCtrl"> <img ng-repeat="pic in pics" ng-src="{{pic}}" /> <form ng-submit="postPic()"> <input id="photos" type="file" accept="image/*" multiple/> <button> ...

Python is unable to correctly query JSON LOAD due to a syntax error

I'm encountering an issue while attempting to retrieve data from the sig API. Despite providing the correct URL, an error is being generated. import requests import json from json import loads import pandas as pd import matplotlib as plt requests.ge ...

Retrieve and save only the outcome of a promise returned by an asynchronous function

I am currently working on an encryption function and have encountered an issue where the result is returned as an object called Promise with attributes like PromiseState and PromiseResult. I would like to simply extract the value from PromiseResult and s ...

Unable to load the file or assembly 'Newtonsoft.Json.Net35

My program is encountering a runtime exception {"An issue has occurred with loading the file or assembly 'Newtonsoft.Json.Net35, Version=4.0.2.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system is u ...

What is the process for retrieving data from a javascript file that was submitted through a form?

Can you help me with an issue I'm having with this code snippet? <form action="main.js"> <input type="text" required="required" pattern="[a-zA-Z]+" /> <input type="submit" value="Submit" /> </form> After c ...

Sending dynamic information to bootstrap's modal using props in VueJS

I'm currently working on a personal project and encountering an issue with the bootstrap modal. My project involves a list of projects, each one contained within a card element. The problem arises when I attempt to display details for each project by ...

Discovering the Desired Key within a JSON Structure

For my c# project, I am utilizing the Json.net Library. Within this library, I have a lengthy JSON object with multiple subfields. Here is an example of the structure: { "count": 10, "Foo1": [ { "id": "1", "name": "Name1" }, { ...

Updating the Highcharts chart when new data is available

Utilizing Highcharts, I am looking to have this chart update every second. Here's my current setup: JSFiddle I've implemented a timer with window.setInterval(updateChart, 1000); which successfully updates data each second. However, I'm uns ...

Struggling to retrieve accurate JSON data from a hashmap using Gson

Utilizing GSON and hashmap to retrieve JSON data from a Pojo class. Here is an example of the Pojo Class: public class NetworkConfiguration { @SerializedName("GUID") @Expose private String gUID; @SerializedName("Name") @Expose pri ...

Leveraging the proxy configuration in React to fetch information from a backend powered by Featherjs

I'm facing a bit of confusion trying to connect my Featherjs backend service, which is running locally on localhost:3030/forms, with a create-react-app client on localhost:3000. In order to establish this connection, I updated the package.json file o ...

What are the steps for extracting data from this Betting API?

With limited experience in handling JSON responses in Android, I am seeking guidance on how to parse JSON data from the following API: https://api.the-odds-api.com/v2/odds/?sport=UPCOMING&region=uk&apiKey=e3b70c1881a5d9eec34e4cb256844874. To begin, ...

Display a div based on user selection using Ajax and Laravel

There are two div elements on the index page containing a datatable. By default, these two divs should be hidden. When an option is selected from the dropdown menu, the corresponding div should be displayed. The webpage is designed for searching within a ...

Using d3 to showcase pictures sourced from a csv file

Having recently embarked on a journey to learn javascript, d3, and the polymer project, I am facing a challenge that I hope to get some guidance on. After successfully parsing a csv file containing image information and creating an array specifically for ...

The element is anchored within a div, but its position is dependent on a JavaScript script

I am dealing with a situation where I have a div named "Main_Card" containing text and an icon. When the icon is clicked, it moves the "Main_Card" along with everything inside of it. The challenge arises when I need to set the icon's position as eithe ...

Fetching a value by key from a JSON object in a Node.js script

How can I extract the id value from this JSON object? answerTag: [ '[{"id":64,"name":"Coronary Artery Disease"}]', '[{"id":64,"name":"Coronary Artery Disease"}]' ], risk: '1' } ...

jQuery: add to either element

What is the most efficient way to use .appendTo for either one element or another based on their existence in the DOM? For instance, I would like to achieve the following: Preferred Method: .appendTo($('#div1') || $('#div2')); Less ...

Adjust the color of the paper in Material-UI

I'm in the process of creating a React project using the material-ui library. Currently, I am facing an issue with customizing the drawer component's background color. After some research, I learned that modifying the paper attribute of the drawe ...

Tips for fixing the TS2345 compilation error when working with React

Attempting to implement the setState method in React has resulted in a compile error. Any solutions to this issue would be greatly appreciated. Frontend: react/typescript articleApi.tsx import axios from 'axios'; import {Article} from '../ ...