Sending JSON objects as parameters to WebMethod

I've encountered various errors while passing parameters to my WebMethod. Below are my attempts and the corresponding errors:

globalData is an array, mapping is an array that can be deserialized to List<Mapping>, selectedFund is an integer.

C# WebMethod

[WebMethod]
public static void ProcessData(string data, List<Mapping> mapping, int selectedFund)
{
    //blah blah
}

Attempt 1

var payload = new Object();
payload.data = globalData;
payload.mapping = chosenMappings;
payload.selectedFund = $selectedFund.val();

$.ajax({
//...etc
data: JSON.stringify(payload),
contentType: "application/json; charset=utf-8",
}

Error: System.String is not supported for serialization of an array.

Attempt 2

$.ajax({
//... etc...
    data: {
        data: JSON.stringify(globalData),
        mapping: JSON.stringify(chosenMappings),
        selectedFund: $selectedFund.val()
    },
    contentType: "application/json; charset=utf-8",

Error: Invalid Json primitive

Answer №1

Make sure to include the content type when using jQuery to post JSON:

contentType: "application/json; charset=utf-8",

For more information, refer to the following article:

http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Answer №2

Solved the puzzle! The solution was to use JSON.stringify() two times. First, outside the function, then inside...

contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: "json",
//data: JSON.stringify(payload),
data: JSON.stringify({
    data: JSON.stringify(globalData),
    mapping: JSON.stringify(chosenMappings),
    selectedFund: $selectedFund.val()
}),

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 to Utilize findIndex to Validate the Presence of Elements in an Array of Objects using TypeScript

I need assistance in checking which properties from an array are present in another array of objects and which ones are not. My object structure is as follows: var tempObj=[{id: '1', color: 'red, blue, green', age: 27},{id: '2& ...

Guide: Using jQueryUI's explode effect to animate an HTML element explosion

I'm having trouble getting the jQueryUI explode effect to work properly. I've tested it out on this jsfiddle, but the explosion effect doesn't seem to happen as expected - the element just disappears with no explosion animation. $('h1, ...

Combining Elasticsearch with AngularJS or Node.js

I am currently developing a MEAN stack application that utilizes elasticsearch for searching records. In my AngularJS controller, I have implemented the following code to interact with the elasticsearch server: instantResult: function(term) { var client = ...

I am facing an issue with my JsonConvert not converting as expected

Currently, I am retrieving data from an API and aiming to transform it into a List of Objects: // Retrieving the data var searchResult = GetResults(); string[] data = (string[]) searchResult.Data; string headers = searchResult.Headers; // Formatting the d ...

Combining and removing identical values in JavaScript

I need to sum the price values for duplicated elements in an array. Here is the current array: var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]] This is what I am aiming for: ...

Exploring the World of Next.js and Sequelize Model Relationships

Greetings to all the problem-solving enthusiasts out there! I'm currently in the process of revamping a previous project using Next.js, and I've hit a roadblock that has me stumped. My current challenge involves establishing an association betwe ...

Error: The value entered for the 'end_time' column in row 1 is outside of the acceptable range

My current scenario involves sending a JSON payload from an Android device to a web-service. The JSON includes two fields, namely startTime and endTime. Both startTime and endTime are of type Long in the DTO classes on both the client and server sides. How ...

Adding a JavaScript variable into a Django template tag

This particular situation has been presenting a challenge for me. So far, I have been using query parameters instead of a variable within the {% url %} tag. However, I can't help but wonder if there is a way to achieve this: I am interested in includ ...

JSON Response Handler

Here is the coding structure I am currently utilizing: func extractData(){ URLSession.shared.dataTask(with:apiURL!, completionHandler: {(data, response, error) in guard let data = data, error == nil else { return } do { ...

`Navigating through database structures using node js`

When it comes to interpreting a Database {} object in JavaScript, I am currently working on back end scripts for validating a registration form. Specifically, I need to make sure that the username and email being used for registration are not already taken ...

Manage shared nested modules across different modules in Vuex without redundancy

In my Vue.js application, I am using Vuex as the state manager. To ensure that certain states are shared across different components, I have created a nested state containing all the common information. This allows me to import it into multiple modules. F ...

Continuous polling with Ajax in Rails does not trigger the display of an alert box

Trying to implement ajax polling using the RailsCast tutorial on ajax polling (#229) but encountering an issue where the alert box doesn't pop up after running the server. Here's the code in app/views/quotes/index.js.erb: alert('Hey') ...

Error: SyntaxError - Issue with the AJAX request

When attempting to retrieve the HTML of a page using the following ajax request: $.ajax({ type: 'GET', dataType:"jsonp", url: link, success: function(response){console.log(response)}, ...

Incorporating traditional Javascript classes for modeling in React development

Can traditional JavaScript classes be utilized in models within the MVC framework while using React, as opposed to relying on Redux or contexts & reducers which may impact reusability? If this approach is feasible, how can we efficiently 'subscribe&ap ...

Tips on connecting data within a jQuery element to a table of data

I am currently developing a program that involves searching the source code to list out element names and their corresponding IDs. Instead of displaying this information in alert popups, I would like to present it neatly within a data table. <script> ...

Having trouble extracting all JSON data on Android when using a URL source

I am facing an issue with retrieving JSON data using a URL in Android. The JSON array I'm working with has multiple values, but when I try to access the length of 'jarray', it shows as 1. Additionally, the length of 'newarr' is dis ...

Adding an external CSS file to your .scss files with webpack: A step-by-step guide

Currently, I am working on a JavaScript application that I am compiling using Webpack. The application is split into two separate bundles - one for the custom code called App and another for the frameworks called Vendor. The App bundle consists of all the ...

List of objects showing the Node Output retrieved from a MongoDB database

{ "dependencies" : [ { "name" : "async", "version" : "2.6.1" }, { "name" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8be9e4eff2a6fbeaf9f8eef9cbbaa5bab3a5b8"& ...

"The JavaScript code included in the index.html file is not functioning as expected when called in the main.js file within a

Here is the index.html code for a simple VueJS app that includes a widget from netvibes.com. The widget code is added in the html file and functioning properly. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC " ...

Define CSS styles based on the content of a specific cell within a table

Is there a way to target a <td> in CSS based on its content value? <table> <tr> <td>Name</td> <td>John</td> <tr> </table> For instance, how can I apply the color:bl ...