What is the reason behind ModelBinding not functioning with FormData but being compatible with RequestPayload?

Recently, while working with Web API, I came across an interesting observation that has left me puzzled.

controller:

$.ajax with additional configurations like type, contentType, accept, the model doesn't bind correctly, whereas it works fine with $.post. Can anyone shed light on WHY this happens?

Answer №1

If you're facing issues, try observing the POST request made using $.ajax (using tools like Fiddler or browser developer tools). It's possible that jQuery may be sending the data as a URL-encoded string instead of JSON format.

To resolve this problem, make sure to set the dataType and contentType parameters. Additionally, there might not be a need for using JSON.stringify; you can simply pass the JSON object directly:

$.ajax({
  data: usr,
  dataType: 'json',
  contentType: 'application/json',
  /* Other configurations go here. */
});

Below is an example of a TypeScript method used in one of our projects (where ko.toJSON converts a JSON literal into a string):

public static callApi(url: string, type?: string, data?: any): RSVP.Promise {
    return new RSVP.Promise((resolve, reject) => {
        $.ajax('/api/' + url, {
            type: type || 'get',
            data: data != null ? ko.toJSON(data) : null,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: () => {
                resolve.apply(this, arguments);
            },
            error: () => {
                reject.apply(this, arguments);
            }
        });
    });
}

Hopefully, this information proves helpful.

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

What is the best way to utilize the initial state in my reducer file?

Every time the user clicks on <Button/>, it saves as FIRST_PERSON_CHOSEN in the database. Instead of using somebody (as defined in the reducer.js file). I want to utilize the initialState within the reducer.js file because currently it seems redund ...

Using MVC4 and dropdown menu with onchange event handler

After researching various posts, I have found methods that should solve my issue. However, I am working in an environment with 3 different servers (Dev, UAT, and Prod), each with its own unique URL structure: http://dev.com/myusername/applicationname (Dev ...

Encountered an Uncaught ChunkLoadError with Vercel Next.js: Chunk 0 failed to load

Upon removing the node modules and package-lock.json files, I encountered the error mentioned above when attempting to reload any page. The project works fine after being restarted for the first time. However, upon reloading the page again, it displays a b ...

Steps for creating a hovering effect that overlays a circular image by 50%

I'm trying to implement a feature on my website where an overlay appears when a user hovers over their display picture. However, I'm facing a challenge as I want the overlay to only cover half of the circle, not the entire photo. After research ...

Unlocking hidden gridview column values with the power of jQuery

Within my gridview control, there are 4 columns, with one column being invisible which contains the Email Address information. <asp:GridView id='gridData' runat='server'> <Columns> <asp:TemplateField> ...

Utilizing AngularJS to display a list of data on a Flot bar chart by triggering a click event

I am relatively new to utilizing angularjs and flot bar chart functionalities. Currently, I am attempting to exhibit filtered data in a curated list upon clicking, based on specified filters. To accomplish this, I have developed a personalized directive ...

ReactNative speech recognition with Google API

Is there an npm package available for implementing Google-like speech recognition? I am looking for one that is compatible with both IOS and Android. https://i.sstatic.net/DfFro.png I'm unsure which npm package to install for this purpose. Any sugge ...

"Making an XMLHttpRequest using the POST method to retrieve and access the response

I'm currently facing a challenge with an ASP.NET Webforms site that I've been working on. After spending 2 hours searching for a solution, and with a deadline looming, I'm hoping someone here can help me out. Within my .cs file, I have the ...

Retrieving the value of a specific <link> in XML using Javascript

I am utilizing Ajax/jQuery to fetch content from an RSS feed, but I'm encountering difficulties in retrieving the content of an XML node named 'link'. Below is a simplified version of the XML: <?xml version="1.0" encoding="UTF-8"?> ...

Using a single function for multiple IDs in JavaScript

function increment(value) { var txtNumber = document.getElementById(value); var newNumber = parseInt(txtNumber.value) + 1; txtNumber.value = newNumber; } function decrement(value) { var txtNumber = document.getElementById(value); var newNumber = ...

Implementing Ruby on Rails to dynamically update search results according to map positioning, integrating data retrieved from JSON files

Currently, I am working on updating search results dynamically on my index page by adjusting the map. The goal is to display only the results that fall within the bounds of the map. I have managed to pass the bounds back to the controller successfully and ...

Enforcing Single Menu Accessibility in React: Only One Menu Open at a Time

Just starting out with React and JavaScript, so please bear with me for any formatting issues or lack of knowledge on best practices. I'm using Tailwind UI for my website, which includes navigation menus that require JavaScript to open and close. I h ...

What is the solution for halting code execution in a foreach loop with nested callbacks?

Currently, I am in the process of setting up a nodejs database where I need to retrieve user information if the user exists. The issue I'm facing is that when I return callback(null) or callback(userdata), it does not stop the code execution and resul ...

Is it necessary to reboot the application server after every modification when working with ExpressJS/Node?

Currently, I am focused on developing Node.JS applications and have chosen ExpressJS as my MVC framework. My main concern at the moment is whether I should restart the server (node app.js) every time I make a change to app.js. If this is necessary, is the ...

Unexpectedly, the kaminari pagination ajax request directs to an incorrect controller

Let's kick things off with the conversations/index.html.haml file to generate a message #new_message_conversation .panel.panel-info .panel-heading %h4 Send a Bark! .panel-footer(style="p ...

Is it possible to seamlessly transition from regular text to italic text?

Wondering if there is a possibility to create a hover effect where regular text, used as an anchor, smoothly transitions into oblique or italicized text with an underline to indicate it is a clickable link. Here's a representation of what I have in m ...

Hiding the div element with 'display: none' causes the disappearance

Whenever I execute this piece of code; document.getElementById("loading").style.display = "none" It unexpectedly hides the div named "myDiv" as well. By setting MyDiv to block, the text appears correctly. However, when loading is set to none, it strange ...

Disrupting methods on a dependency within QUnit can cause tests against that dependency to fail

Currently, in my Google Apps Script project, I am unit-testing an application using QUnit for test-driven development purposes. Code Under Test The function I am currently focusing on testing and developing is the creation of a Sheet from a long string o ...

Setting Absolute URLs in AngularJs using $location

I am currently working on a website where the URL structure is sitename.com/path1/path2. I am looking to use AngularJS to change path1 dynamically. While I have successfully implemented functionality to update path2 using $location.path function, I am un ...

How can we efficiently organize Vue components within one another?

Currently, I am working on a Vue project that consists of multiple pages. While I have managed to make everything work so far, I am facing some challenges with nesting views within each other. Specifically, I have a main homepage view and a subpage view. ...