Performing a JavaScript AJAX request to send a complex object containing an array of other complex objects within it

My issue arises from encountering an empty array of objects at the backend. To illustrate, I have established two classes at the backend...

    public class ScoreModel { 
        public string Subject { get; set; }
        public float Score { get; set; }
    }
    public class StudentTestModel
    {
        public string Name { get; set; }
        public ScoreModel[] Scores { get; set; }
    }

Within the above code snippet, the StudentTestModel class possesses an array of ScoreModel with two simple data attributes. Subsequently, in the frontend, I utilize the jQuery library to interact with the backend in this manner...

$("#btnCountScore").click(function () {
                var frm = new FormData();
                frm.append("Name", "Garfield");
                var r = [
                    { "Subject": "Chinese", "Score": 89 },
                    { "Subject": "English", "Score": 87 },
                    { "Subject": "Math", "Score": 76 },
                    { "Subject": "NaturalScience", "Score": 90 },
                    { "Subject": "SocialScience", "Score": 83 },
                ];
                var r_form = [];
                for (var i = 0; i < r.length; i += 1) {
                    var f = new FormData();
                    f.append("Subject", r[i].Subject);
                    f.append("Score", r[i].Score);
                    r_form.push(f);
                }
                frm.append("Scores", r_form);
                $.ajax({
                    url: "../Home/CountScore",
                    method: "post",
                    processData: false,
                    contentType: false,
                    data: frm,
                    success: function (ret) {
                        $("#lblShowAverage").text(ret);
                    }
                });
            });

During debugging, while the Name field contains value, the Scores array arrives as empty at my backend, hence impeding me from achieving desired results. Is there any guidance available on rectifying this scenario?

Answer №1

Did you consider converting the object to JSON format before sending it, and then deserializing it on the backend?

On the FrontEnd: Use JSON.stringify(frm)

On the Backend: Deserialize the jsonString using JsonSerializer.Deserialize()

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

Does anyone know of a convenient tool that can automatically provide suggested street names for mailing addresses in every country across the globe, for free?

Is there a convenient tool that automatically completes street addresses for various countries worldwide? I'm considering options similar to YQL from Yahoo or Foursquare. I'd like to provide users with suggestions of known street names as they ...

The current error message states that the function is undefined, indicating that the Bookshelf.js model function is not being acknowledged

I have implemented a user registration API endpoint using NodeJS, ExpressJS, and Bookshelf.js. However, I encountered an error while POSTing to the register URL related to one of the functions in the User model. Here is the code snippet from routes/index. ...

The disappearing act of the Show/Hide Button in Sencha Touch 2.3.1: what's the

I'm running into an issue with my sencha touch app. Here is the container I have defined: { xtype: 'container', text: 'SOMETHING', height: '15%', width: '15%', ...

The "click" event is only effective for a single use

I am looking for a way to trigger the click event more than once in my project. I attempted using "live" but it didn't work as expected. There are 2 other similar scripts in this Django project. If you have any suggestions on improving this project, p ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

Unspecified binding in knockout.js

As a newcomer to JS app development, I am currently focused on studying existing code and attempting to replicate it while playing around with variable names to test my understanding. I have been working on this JS quiz code built with KO.js... Here is my ...

Creating a POST method in AngularJS

Here is the code snippet I am working with: var req = { method: 'POST', url: '/customer', headers: { 'Content-Type': 'application/json' }, data: { test: 'testvalue' } }; $http(re ...

Implementing an onclick function to initiate a MySQL update query

<?php include_once("db.php"); $result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'"); while($row=mysql_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['ptype'] . "</td>"; echo "<td>" . $row[&apo ...

Is there a way to dynamically change the source of an image based on different screen sizes using Tailwind CSS?

Currently, I am utilizing the next/Image component for setting an image and applying styling through tailwindcss. However, I have encountered a roadblock at this juncture. My Objective My goal is to dynamically change the src attribute of the image based ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

Efficient method for retrieving the values of each cell in a row within an array

I've got a standard table here - 6 columns, multiple rows, all filled with data. Right now, my goal is to collect all this table data into an array: tableData(0) = "1, Hans, Testperson, Munich, Germany" tableData(1) = "2, Petra, Tes ...

Having trouble with the copy to clipboard function of Prism JS on my NextJs application

I am facing an issue while trying to integrate a copy to clipboard plugin from prismjs into my next.js app. I have searched for documentation on this but couldn't find any relevant information. Despite going through various websites and implementing t ...

Tips for transferring data and events between named views within Vue Router

I have a layout structured like this: .------------------------+----------------. | Current Tab Title | Controls | +------------------------+----------------+ | Tab1 Tab2 [Tab3] | +---------------------------------------- ...

The value of a Casebox object field is determined by the value of another field within the same parent

Currently, I am working with a CaseBox object that contains one field (age) which is supposed to be dependent on another field (birthdate). Based on the documentation for developers, it seems like I need to set age as type Objects, create a server-side fun ...

Downloading PDF files on IOS while using Angular often results in the PDF opening in the same

I'm currently utilizing file-saver within my Angular application to retrieve a PDF generated from the backend. The library functions smoothly on desktop and Android devices, but I'm encountering issues with downloading files on iOS. Contrary to w ...

Uncover the hidden message in a string encoded for JavaScript

This encoded HTML code is intended for use in a JavaScript function <div class=\"ProductDetail\"><div style=\"width:780px\">\r\n\t<div class=\"baslik\" style=\"margin: 0px; padding: 5px 10px ...

Tips on how to trigger the function upon receiving the response value by concurrently running two asynchronous functions

export default { data: () =>({ data1: [], data2: [], lastData: [] }), mounted() { asynchronous1(val, (data)=>{ return this.data1 = data }) asynchronous2(val, (data)=>{ return this.data2 = data }) f ...

Using both ng-if and ng-click in AngularJS for enhanced functionalities

There's a button that should display a toggle only when the value is greater than 0; otherwise, it shouldn't do anything. This snippet of code shows how things were prior to adding ng-if: <span >{{values.valuesNumber}} <i class= ...

Creating separate versions (development and production) of JavaScript code: a step-by-step guide

I have been working on a small web application that is distributed in a Docker container, using an nginx image. This application consists of plain html and js code, without any frameworks. Within the JS code, there is access to a remote host via WebSocket ...

Customizing the layout of specific pages in NextJSIncorporating

In my Next.js project, I'm trying to set up a header and footer on every page except for the Login page. I initially created a layout.tsx file in the app directory to apply the layout to all pages, which worked fine. However, when I placed another lay ...