Sending KeyValuePair or IDictionary as payload to Web Api Controller using JavaScript

In my web api controller, I am trying to post two parameters: a flat int ID and an IDictionary (or similar equivalent).

[HttpPost]
public void DoStuff(int id, [FromBody]IDictionary<int, int> things)
{
}

var things = new Array();
things.push({ 1: 10 });
things.push({ 2: 11 });
$.ajax({
    url: '/api/DoStuff?id=' + id,
    data: '=' + JSON.stringify(things),
    type: 'POST',
    dataType: 'json'
});

Despite multiple attempts with different ways of passing the data parameter (data: things, data: '=' + things), the Dictionary doesn't get passed correctly to the api controller. It shows up as null or with incorrect values ({0, 0}).

I also attempted to send the Dictionary in the Uri but was unsuccessful.

Any suggestions on how I can successfully pass the dictionary or key value pair to the api controller?

Answer №1

If you're looking to avoid using an array and instead use a simple JS object (similar to a dictionary), you can achieve your goal with the following code snippet:

var items = {};
items['1'] = 10;
items['2'] = 11;
$.ajax({
    url: '/api/DoTask?id=' + id,
    data: JSON.stringify(items),
    contentType: 'application/json'
    type: 'POST',
    dataType: 'json'
});

Answer №2

Here is a solution that I found effective:

let configurations = [];
configurations.push({ parameter: "configuration01", setting: "Setting01" });
settings.push({ parameter: "configuration02", setting: "Setting02" });

Answer №3

Even though this is an old method, I once used JavaScript to create an object similar to @cesardaniel's approach:

var dictionary = [];
dictionary.push({ key: 1, value: [1,2,3,4,5] });
dictionary.push({ key: 2, value: [6,7,8,9,0] });

However, when working with .NET, my object shape was of the type

Dictionary<KeyValuePair<int, IEnumerable<int>>
. Thankfully, the web API was able to interpret it correctly. Hopefully, this information will be useful for any future readers!

Answer №4

When working with dictionaries, think of them as key-value pairs similar to an array. To properly send data, you can use the following syntax:


var data = {}
data['things[0].Key'] = x
data['things[0].Value'] = y
// etc

For JavaScript, your code should resemble something like this:


    var data = { };
    data['things[0].Key'] = 1;
    data['things[0].Value'] = 1;
    data['things[1].Key'] = 22;
    data['things[1].Value'] = 12;

    $.ajax({
        url: '/api/DoStuff?id=' + id,
        data: data,
        type: 'POST',
        dataType: 'json'
    });

The action on the server side should look similar to this:


    public ActionResult DoStuff(int id, Dictionary<int, int> things)
    {
        // ...
    }

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 steps should I take to resolve the issue with running npm start?

I am encountering an issue while using React and trying to run my application. When I execute "npm run start," I receive the following error message: npm ERR! Missing script: "start" npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark ...

"Here's a simple guide to generating a random number within a specified range

I have encountered a specific issue: Within an 8-column grid, I am attempting to randomly place an item with a random span width. While I have successfully managed to position the item and give it a random width, I am struggling with adjusting the width b ...

Is Cognito redirect causing issues with Angular router responsiveness?

When employing social login via AWS Cognito, Cognito sends a redirect to the browser directing it to the signin redirect URL after signing in. In this case, the specified URL is http://localhost:4200/home/. Upon receiving this redirect, the application in ...

Executing a function immediately upon the start of a new month in JavaScript (Node.js) without relying on any external libraries?

Is it possible to automate the process of creating a document in MongoDB using Mongoose every 1st of a new month, ideally as soon as the date changes without relying on third-party libraries like needle or cronjob? Can this be achieved solely with setInter ...

Troubleshooting Django Templateview: Incorporating Bootstrap Popovers into HTML tables not functioning properly

https://i.stack.imgur.com/LXHJF.pngWhen loading this template, the HTML renders correctly and the table loads successfully. However, certain cells have special pop-over attributes that do not work after the HTML is loaded via an AJAX request on the same pa ...

What is the best approach for incorporating sub-navigation within a page popup in a Next.js project?

In the midst of my Next.js project, there is a requirement to showcase a chat popup consisting of multiple sub-pages like user registration, conversation page, and more. Hence, seamless navigation inside this popup is necessary. The idea is not to alter th ...

Leveraging JSON encoded data returned through AJAX in Codeigniter

Having recently started with codeigniter, I encountered an issue while trying to perform a search operation on my database using AJAX. The code execution was successful and the data was retrieved. However, the data is JSON encoded and located in the javasc ...

What is the process for creating a sub-menu for a dropdown menu item in Bootstrap 5?

https://i.sstatic.net/o4FLn.pngthis is my code which i have created this navigation bar with bootstrap and all of its drop downs but i want to add another drop down to the services drop down section inside of webdevelopment but it can't any easy solut ...

Updating the configuration settings for CKEditor 5 using Reactjs

I followed the configuration provided in another answer at But, I am facing an issue: Failed to compile. ./src/components/cards/CreateCard.js Line 59:22: Parsing error: Unexpected token, expected "}" 57 | editor={ClassicEditor} 58 | ...

The header that sticks on scroll is annoyingly blocking the content

I managed to create a sticky on-scroll header/navigation bar successfully. Here is how it looks now However, I encountered an issue. When it reaches the top, it automatically 'covers' the top part of my content, which has text on it, and I don& ...

Is it possible to directly access my JSON object in .ajaxSuccess without needing to parse it?

My CoffeeScript code includes an ajax call that functions properly: ajaxElement.change -> $(this).data('request','initiated') $.ajax type: 'PUT' url: $(this).closest('form').data('update-url&apos ...

Tips on choosing and duplicating solely numerical values from a designated element

Can someone assist me with a minor issue? I am attempting to specifically select and copy only the numbers from an element, then paste them into another location. Is there a way to utilize Selenium with C# to isolate and highlight just the numbers within ...

Exploring methods to conduct testing on an AngularJS application using AngularJS end-to-end testing, specifically focusing on scenarios involving multiple inputs

Our program includes a directive that is repeated multiple times with an input field. The structure of our code resembles the following: <li> <label>AMI</label> <div class="searchbox" searchbox="" filter="search.ami"> ...

What is the best way to retrieve the most recent CMS posts information within a Gatsby-constructed project?

I created a static website using Gatsby and everything was working well. However, I encountered an issue when updating the titles and content of posts in Contentful CMS - the changes were not reflected when I refreshed the website. How can I ensure that ...

Is it possible to swap out images using srcset attribute?

Currently, I am facing an issue regarding changing the img on mobile and tablet devices to display different images. As a beginner with jQuery, I couldn't resolve it using that framework, so I am exploring options with html5. I am wondering if there ...

The clash of interests between jQuery and Bootstrap

I'm facing a problem with conflicting jQuery and Bootstrap files in my header.php code. Whenever I include the jQuery file before the bootstrap.js file, it causes issues with the tabs on my website where clicking on them does not navigate me to the co ...

Creating an Array in AngularJS with ng-model and submitting it with jQuery: A comprehensive guide

I am struggling to submit an array of values using jQuery and AngularJS. Whenever I click the submit button, only the first array value is being retrieved. How can I get all array values using ng-model? Here is a link to all my code: https://jsfiddle.net/r ...

Tips for transfering variables from an electron application to the backend of an Angular project

My goal is to develop a website and desktop application using the same code base. However, due to some minor differences between the two platforms, I need a way for my Angular app to distinguish whether it has been called from the web or from Electron. I& ...

Transforming JSON/XML into a hierarchical display

I've come across the following XML file: <Person attribute1="value1" attribute2="value2"> value3 <Address street="value4" city="value5">value6</Address> <Phone number="value7" type="value8">value9</Phone> </Pers ...

After sending a GET request in AngularJS, simply scroll down to the bottom of the

Usually, I use something like this: $scope.scrollDown = function(){ $location.hash('bottom'); $anchorScroll(); } While this method works fine in most cases, I've encountered an issue when fetching data for an ng-repeat and trying t ...