Can I send an array of JavaScript classes to an MVC controller?

I'm struggling to pass an array of services to my controller. I've experimented with different methods, like serializing the data before sending it to the controller, serializing each service individually, and converting the controller parameter to a string and then serializing the array using JsonConvert. The latter approach seems to work, but I would prefer not to do it this way.

The current code results in the correct number of items in the List, but they all have a service ID with an empty guild and the service provider ID is null.

Any suggestions on how to resolve this issue?

Javascript


function ServiceItem() {
    this.ServiceProviderID = 'all';
    this.ServiceID = '';
}

var selecteditems= (function () {

    var services = new Array();

    return {
       all: function() { 
           return services; 
       },
       add: function(service) {
           services.push(service);
       }
    };

})();

var reserved = [];
$.each(selecteditems.all(), function(index, item){
   reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});

getData('Controller/GetMethod', { items: reserved }, function(result) {
});

var getData = function (actionurl, da, done) {
       $.ajax({
           type: "GET",
           url: actionurl,
           data: da,
           dataType: "json",
           async: true,
           success: function (d) {
               if (typeof (done) == 'function') {
                   var str = JSON.stringify(d);
                   done(JSON.parse(str));
               }
           }
       });
};


Controller

public JsonResult GetMethod(List<CustomObject> items)
{
}

Custom Object

public class CustomObject
{
   public Guid ServiceID {get;set;}
   public Guid? ServiceProviderID {get;set;}
}

Answer №1

To ensure proper data transmission, make sure to set the content-type and switch from GET to POST, especially when dealing with a list of complex type objects. Don't forget to annotate your action with the HttpPost attribute.

Try the following code snippet to see if it resolves the issue:

 $.ajax({
           type: "POST",
           url: actionurl,
           data: JSON.stringify(da),
           dataType: "json",
           contentType: 'application/json',
           async: true,
           success: function (d) {
               if (typeof (done) == 'function') {
                   var str = JSON.stringify(d);
                   done(JSON.parse(str));
               }
           }
       });

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

Creating nested JSON using xpath by utilizing SmarGWT's DynamicForm and Form items

I have successfully set up a SmarGWT datasource that retrieves nested JSON data like this: {username:"tom",password:"pwd",userType:{id:1,name:"admin user type"}} The DataSource is configured with the following fields: DataSourceTextField usernameField = ...

Implementing Ajax calls in Spring Boot with Thymeleaf

I am attempting to make a Spring Boot controller call from an Ajax Request: $('#female').click(function(){ $('#analysisTable').DataTable( { "ajax": '/analyse/female' }); }); The purpose of this is to populate a ...

Personalized Guzzle serialization

Need help with custom serialization in Guzzle. Trying to send a POST request with application/json content, but the object is being serialized with its name (professionalSession) at the beginning: { professionalSession : { param1 : "asdf", par ...

How do I leverage one of my props in React to iterate through my JSON data?

My goal is to utilize props.type to modify the mapping of the JSON in the H5 section. I attempted to accomplish this similar to how I did with the className, but unfortunately, I haven't been able to find the correct method. import text from "../ ...

Error: The property "indexOf" cannot be accessed because n is not defined

After rendering a page and retrieving data from Firebase upon clicking a button, I encounter an error upon refreshing the page: Unhandled Runtime Error TypeError: can't access property "indexOf", n is undefined Source pages\[id].js (1 ...

Experiencing a problem with obtaining the .offset().top value of an element within an iframe resulting in an

Encountering an issue with Firefox and Safari where attempting to retrieve the .offset().top value from an element within an iframe results in undefined when trying to access this value. This functionality seems to be working properly in Chrome, Edge, and ...

What are some ways to manipulate JSON data following a successful AJAX request?

I've been grappling with this issue for quite some time now, trying various methods without any success. I won't bore you with the details of my failed attempts, but instead, I'll show you the code I'm currently working with. Here' ...

Transforming the data retrieved from the API into a well-organized object in Vue.js

Currently, I am utilizing the vue-meta library to incorporate meta tags into my Vue project. What I'm attempting to do now is populate my meta tags using the API response data. Here's an example output from the API when I log 'response.data. ...

Encountering an issue when running the 'cypress open' command in Cypress

I am working with a Testing framework using node, cypress, mocha, mochawesome, and mochawesome-merge. You can check out the project on this github repo. https://i.sstatic.net/ItFpn.png In my package.json file, I have two scripts defined: "scripts": { ...

Why is it that despite passing all the unit tests successfully, the function fails when used in its actual context with the same parameters?

I have created a basic API to encrypt text using the Caesar cipher in Javascript with Express.js. While running tests with Jest, it seems that all the tests are passing successfully (and a console.log of the output confirms that the resulting string matche ...

Assign a value to a hash object based on a specific location stored within an array

I'm struggling to figure out how to retrieve the original JSON data when its structure is variable. var jsonData = { "parent": { "child": "foo" } }; fu ...

Tips for enabling/disabling a Chrome extension through the utilization of local storage in the background page

Even after reading numerous answers on similar questions, I am still facing some difficulties. My goal is to allow the user to disable my chrome extension by simply clicking on the icon at any time. The extension is designed to run once on every page load, ...

Why does the text in a div display in Safari 8.2 and Chrome 39, but not in Firefox 34?

In my HTML document, I have a div tag located within the body like so: <div id="content_text"></div>​ Using javascript, I later set the contents of the div like this: var content_text = document.getElementById("content_text") c ...

What is the best way to transfer data between two different JSON schemas using Python?

One day, I stumbled upon a json schema that appeared like this: Country:{ city:{ value1:0, value2:1, value3:2, value4:3, value5:4, value6:5 } ...

Exploring First-Person Shooter Rotation with THREE.JS

I recently attempted to create a rotation system for a First Person Shooter game using THREE.JS. However, I encountered a strange issue where the camera would pause momentarily before returning, especially at certain rotations. When checking the rotation ...

Encountering an issue while attempting to iterate through JSON response

After receiving a JSON response from the server: [{"id":605,"vote":1},{"id":606,"vote":-1},{"id":611,"vote":1},{"id":609,"vote":-1}] I attempt to iterate through the results and access the properties of each object: success: function (data) { $.each(da ...

When using the dict update method in SQLAlchemy, how does it affect the Object-Relational Mapping (ORM

Recently, I encountered an issue with a SQLAlchemy Table that had a JSON column: from sqlalchemy.dialects.postgresql import JSON class MyTable(db.Model): id = db.Column(db.Integer, primary_key=True) my_json_column = db.Column(JSON) My attempt to ...

Dealing with JSON errors in Flask with try-except block

I have been working on adding a DELETE method to an API, but I am encountering issues. Here is the code snippet I am using: if request.method == 'DELETE': if request.headers['Content-Type'] == 'application/json': ...

The initial state in NextJS fails to update when routing to the same page with different parameters

This particular project utilizes NextJS The structure of my page's URL is as follows: localhost:3000/first/second When I invoke getInitialProps on this page, the data retrieved from it is passed to the component and used to set the initial state li ...

Why are NodeJS and Jade/Pug variables not being recognized in the Jade script?

After successfully passing a variable to Jade like #{myvar}, I encountered an issue when trying to access it in a script block. Despite using typeof(myvar) and confirming that it was initially undefined, my attempts to display its value within the script b ...