Data Structure - Java, Python, ReactJS

I have a loop in my code that populates an array, with the parameter 'cont' being passed from the View

function GenerateJSON(cont) {
        var songs= [];

        for (var i = 0; i <= cont; i++) {
            songs[i] = {
                id: i,
                genre: $(".genre" + i).val(),
                song: $(".song" + i).val()
           }
        }
        $.ajax({
            url: "Generate",
            type: 'POST',
            dataType: "json",
            data: { songs: JSON.stringify(songs) },
            success: function (data) {
            }
        })
    }

In the Controller, I am only receiving one block of music

For example:

songs= [{"id":0,"genre":"","song":"","id":1,"genre":"","song":"","id":2,"genre":"","song":""}]

Instead, I would like it to be structured as follows:

songs=[{"id":0,"genre":"","song":""},{"id":1,"genre":"","song":""},{id":2,"genre":"","song":""}]

Controller

public JsonResult Generate(string[] songs)
    {}

Answer №1

It seems using a string array as the parameter may not be the most efficient approach. You would need to write client-side code to construct complex strings and then parse them on the server side to extract property values for each item.

Instead, I suggest utilizing a view model and taking advantage of MVC model binding. Begin by creating a view model to represent your data structure.

public class SongVm
{
    public int Id { set; get; }
    public string Genre { set; get; }
    public string Song { set; get; }
}

Then use this view model as the parameter in your action method. If you are sending a collection of objects, specify List<SongVm> as the parameter type.

[HttpPost]
public ActionResult Gerar(List<SongVm> songs)
{
    // Return the data with a message property
    return Json(new { messge ="success", data = songs });
}

In your client-side code, convert your array into a JSON string and set the contentType property to application/json before passing it to the $.ajax method.

var songs = [];

for (var i = 0; i <= cont; i++) {
    songs[i] = {
        id: i,
        genre : "test genre" + i,
        song : "test song" + i
    };
}

$.ajax({
        url: "/Home/Gerar",
        type: 'POST',
        contentType: "application/json",
        data: JSON.stringify(songs),
        success: function (data) {
            console.log(data);
        },
        error: function (a, b, c) {
            console.log(c);
        }
 })

The $.ajax method will include the request header Content-Type: application/json. This helps the default model binder to read the data from the request body and bind it accordingly.

Additionally, consider using Url helper methods like Url.Action to generate the correct path to the action method.

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

methods for obtaining access in JavaScript when dealing with an ArrayList<Object> that has been converted to a JSONArray

I am dealing with an Object ArrayList that contains various variables, stored in an ArrayList of Objects. I then convert it to a JSONArray and pass it to a JSP page. How can I display these objects in a textarea on the JSP page using JavaScript? public cl ...

Encountering an Error with Polymer 1.0 and Django: Unresolved Reference to KeyframeEffect

I've been experimenting with Polymer 1.0 in combination with django and snapdragon. Although I've managed to render the elements successfully, I've hit a roadblock when it comes to animations. The code I'm using is almost identical to t ...

The error thrown is: ProgrammingError - (psycopg2.errors.UndefinedObject) "json" type is not found

I need help uploading a pandas table with a json column into redshift. Here is a simplified version of my code: from sqlalchemy import create_engine from sqlalchemy.types import JSON import pandas as pd RS_creds = {} RS_creds['host'] = %env RS_ ...

Is there a way to enable Intellisense tooltips in Visual Studio to display descriptions specifically for .NET Framework 3.5?

For my current project, I need to utilize the .NET framework 3.5 due to its reliance on older functionality. However, when working in Visual Studio I noticed that the tooltips are not displaying comprehensive descriptions as they normally would with a mor ...

Transforming a pandas dataframe into a nested dictionary or JSON structure

I have been attempting to convert the following pandas dataframe(python) into a nested dictionary format. Input data pandas dataframe: statetraffic |state | act | traffic| reward | header | time | id stateacttraf | 1 | 1 ...

Using the Ajax method from a separate class in TypeScript: A step-by-step guide

Recently, I started learning about typescript and ajax. One of the challenges I encountered was while creating a method in typescript for making ajax calls that can be used across classes: myFunc(value: string): JQueryPromise<any> { var dfd = $. ...

Error: Unable to use the map method on data in Reactjs because it is not

I'm currently working on a project with React.js and using Next.js as well. I'm attempting to fetch data from an API, but I keep encountering the following error: TypeError: data.map is not a function Below is the code snippet from the Slider.js ...

The processing indicator fails to function properly when trying to refresh a jQuery datatable

I am currently customizing the loading indicator for the datatable using a spinner called startLoadGlobal(SPINNER_DATA_TABLE_FINANCEIRO_CARREGAR_REGISTROS) in jQuery. It works correctly when I initially load the datatable, however, when I reload it, the sp ...

Want to learn how to create an image magnifier using just one image?

At first, I created an image magnifier that would zoom in when the user hovered over the image. However, now I am looking to switch to a lens zooming method that uses only one image. ...

Issue with verifying Apple SSO title using SpecFlow and Selenium

When working with Apple SSO, I have encountered an issue with the title containing a special character that causes my assertion for "Sign in with Apple" to fail. I have attempted using regex replace but it has proven ineffective. The failure message reads ...

Having difficulty accessing the 'makeCurrent' property of an undefined object in Angular mobile application

I have followed the steps outlined in the Angular mobile toolkit guide found at https://github.com/angular/mobile-toolkit/blob/master/guides/cli-setup.md My Node version is v4.4.3 NPM version is 2.15.1 The issue arises when I run the command $ ng serve, ...

How can I make the footer on my webpage have a white background?

My goal is to create a white div that spans from point (A) to point (B) on the page, just like in the image. I aim for it to stretch all the way down to cover the entire browser without showing any gray background underneath, even when the page is scrolled ...

Loading items into multiple containers using PHP AJAX pagination

I'm looking to implement a "load more" button on my website, but I'm facing a challenge due to my three-column layout. I want to load more items into their respective parent elements without disrupting the design. While I've used infinite aj ...

What was the reason for the removal of the `encoding` keyword argument from json.loads() function in Python 3.9?

The json package's official documentation explains: json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶ As of version 3.6: The s parameter now supports bytes or bytear ...

Incorporate new markers into Google maps without the need to constantly initialize the map

My current goal is to have the user input a latitude and longitude into a text box, and then display a marker on the map for that location without needing to reinitialize the map each time. To start, I have set up my map like this: <script type="text/ ...

Is it possible for Node.js to execute individual database operations within a single function atomically?

As I delve into writing database queries that operate on node js, a puzzling thought has been lingering in my mind. There seems to be a misunderstanding causing confusion. If node is operating in a single-threaded capacity, then it follows that all functi ...

Struggling with converting a Dictionary to an Array

Every time I include this specific line of code, my application crashes. self.cartProducts = responceDictionary!["result"] as! [AnyObject] The variable responceDictionary is holding JSON data that needs to be stored in an Array as type AnyObject. I&apos ...

Uploading files with Vue.js Element-UI and axios triggers unwanted page refresh

I am utilizing the element-ui file upload component() to manage the frontend of image uploading. All functionalities work flawlessly (file is successfully sent to the server, etc). However, for some reason, after the axios's successful response code r ...

What is the best way to utilize the sx prop in Material UI for applying styles specifically when the component is active or selected?

In the code snippet below, I have set up the useState hook so that when a ListItem is clicked on, the selected state becomes true. My goal is to apply specific styling when an item is selected using the sx prop instead of creating a styled component for su ...

Methods to prompt a user to select an option using Bootstrap

I have been struggling with this problem for hours and it's really starting to frustrate me! Currently, I am incorporating Twitter Bootstrap along with bootstrap-min.js. This is the code snippet in question: <select id="assettype" name="assettyp ...