Guide for passing two arrays to the view at the same time using JSON in asp.net MVC

I need assistance with creating a dynamic chart in my view. The chart should be based on a value entered by the user in an input field within a form. I am using Ajax and Json to handle this asynchronously. After sending the user input to the controller, my code generates two arrays: one string array for the chart labels and another int array for the data values.

My problem is that I can only send one of these arrays at a time and cannot figure out how to send both. I have read suggestions about sending the arrays as a collection, but I'm unsure if this is the correct approach.

Here is a simplified version of the code in my controller:

public ActionResult DoChart(string data)
{
    string[] product = {"Bread", "Milk", "Eggs", "Butter"};
    int[] quant = {10, 20, 30, 40};

    return Json(product, JsonRequestBehavior.AllowGet);
}

Below is the Javascript code in my View:

<script>
$(function() {
    $("form#chartForm").on("submit", function(e) {
        e.preventDefault();
        let obj = {
            quantity: $("#quantity").val()
        };
        $.ajax({
            url: "@Url.Action('DoChart')",
            method: "GET",
            data: {
                data: JSON.stringify(obj)
            },
            success: function(product, status) {
                alert(product);
                var ctx = document.getElementById('myChart').getContext('2d');
                var myChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: product,
                        datasets: [{
                            label: '# of Votes',
                            data: [1,2,3,4,5,6,7,8],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                        }
                    }
                });
            }
        });
    });
});
</script>

In the code above, I am currently sending the product array to set the chart labels. However, I want to also send the quant array to set the data values for the chart.

Any help or suggestions would be greatly appreciated. Thank you!

Answer №1

At first, ensure you have a container for your outcome. As an illustration, you could establish a custom container like the following

 public class OutcomeHolder
        {
            public string[] Items { get; set; }
            public int[] Amount { get; set; }
        } 

Handler

You can populate the values of the OutcomeHolder from your handler. It encompasses two arrays, one for items and one for quantity.

public ActionResult ProcessData(string data)
        {
            string[] products = { "Apple", "Banana", "Orange", "Grapes" };
            int[] quantities = { 5, 15, 25, 35 };

            var outcomeHolder = new OutcomeHolder()
            {
                Items = products,
                Amount = quantities
            };

            return Json(outcomeHolder, JsonRequestBehavior.AllowGet);
        }

AJAX Triumph script

The AJAX response comprises of two arrays. You can integrate these into your chart.

 success: (result, status) => {
                    alert(result.Items);
                    var canvas = document.getElementById('myChart').getContext('2d');
                    var myDiagram = new Chart(canvas, {
                        type: 'bar',
                        data: {
                            labels: result.Items,
                            datasets: [{
                                label: '# of Quantity',
                                data: result.Amount,
                                borderWidth: 1
                            }]
                        },
                        options: {
                            scales: {
                                yAxes: [{
                                    ticks: {
                                        beginAtZero: true
                                    }
                                }]
                            }
                        }
                    });

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

Ensuring the authenticity of a Node.js model through the utilization of

Recently, I've been working on developing a NodeJS application using JavaScript and MySQL. As the object I'm handling started to grow in complexity making it difficult to read, I received a recommendation to implement the builder pattern. In resp ...

Inverted Binding Checkbox: A new twist on checkbox functionality

In my software system, I have defined two main entities: Customer and User. Here is the structure of these entities: public class User { [Key] public int Id { get; set; } [StringLength(20)] public string CustomerId { get; set; } public ...

Python Program for Extracting Data from JSON File and Assigning it to Variables

Greetings, I am encountering an issue with the following code snippet where I am trying to extract values from a JSON file and assign them to variables: with open('C:/files/response.json') as json_file: data = json.load(json_file) for item i ...

How can I insert <div> elements into arrays in JSX?

I am currently learning React through a tutorial that involves creating a tic-tac-toe game. The tutorial initially renders the game board by hard-coding a list of <div> elements, as shown below: render() { return ( <div> ...

Enable the duplication of strings within an array

Below is the HTML code snippet I am working with: <div class="col-sm-8"> <div class="row col-sm-12 pull-right paddingDiv"> <div class="col-sm-12"> <div class="marginBottom pull-right"> <bu ...

Leveraging the power of AJAX and JSON to showcase dynamic HTML content pulled from PHP

I'm working on retrieving data from my PHP file, and it contains information in the columns Email, FirstName, LastName, and State. $query = 'SELECT * FROM users WHERE LOWER(Email) = :email'; $stmt = $dbh->prepare($query); $stmt->bindV ...

No matter what I attempt, my presentation refuses to align in the center

My slideshow, which is powered by jQuery/JS and involves absolute positioning for each image, is causing me trouble when trying to horizontally center it on the page. No matter what I do, I can't seem to get it right. The challenge is not only getting ...

Struggling to convert my VueJS component from JavaScript to TypeScript, feeling a bit lost

I am new to VueJS and I am facing a challenge converting my VueJS project to use TypeScript. I have been trying to bind functions to certain variables in JavaScript, but I am struggling with accomplishing the same in TypeScript. Even though there are no er ...

AngularJS: Challenges with Binding in event handlers within ng-repeat loops

I'm currently working on a project where I need to display buttons for choosing a username using ng-repeat. The display of the buttons is working fine, however, I have encountered an issue with the ng-click directive within the loop. Even though the b ...

Next JS encountered an error - Error [ERR_HTTP_HEADERS_SENT]: It is not possible to set headers after they have already been sent to the

Having crafted a serverless application using next.js, Vercel, and Google Sheets to store customer contact data, I encountered an issue post-deployment. While my application works flawlessly locally, after deployment, I started receiving the following erro ...

Escaping latitude and longitude coordinates using PHP

I am looking to include longitude and latitude values in a json file. However, the current code I have escapes the values and adds quotation marks. Example of json output{"votes":["{\"lat\":\"51.426799\",\"lng\":\"-0.331 ...

Express: issue retrieving numbers from request body array

JavaScript / TypeScript Issue: export const updateSettings = catchErrors(async (req, res) => { console.log("updateSettings req.body: ", req.body) const { organizationId, formdata, updatedItems, updateQuota } = req.body; console.lo ...

JQuery - Automatically loads all elements when the page is loaded

I have incorporated some jQuery to toggle the visibility of certain elements on my webpage. However, upon page load, both elements are displayed simultaneously. It is only after interacting with the menu or options that the functionality works as intended. ...

Injecting randomness into webpage backgrounds with Flickr API

How can I use the Flickr API to display a random photo tagged with "landscape" on my website? I've tried inspecting the HTML using Chrome DevTools, but no photo is showing up. What am I missing? $(document).ready(function() { $.getJSON("https:// ...

``In JavaScript/Node.js, I am experiencing an issue with an ajax POST request where the object

I'm having trouble sending a JSON object to my server. When I check the console log for req.body, it's showing up as an empty object. Here's the code snippet in question: var submitRecipe = () => { let recipe = {alias: null, descrip ...

Creating a function for loading dynamic content in XSLT can be achieved by following these steps

When I call the function collapseandexpand() for static elements only, it does not work. Now, how can I create the same function to handle dynamic content in xslt? Javascript Code: <script language="javascript" type="text/javascript> <xsl:text&g ...

Using jsTree to Connect to Objects in a Domain

I'm looking for a way to link each node in my tree with a domain object. Previously, I was passing HTML data and storing the domain object manually using jQuery data: $('li node description').data('obj', my_domain_object); Howeve ...

There was a parsing error due to encountering an unexpected reserved word 'interface' in the code, as flagged

I'm encountering an issue with my code when trying to utilize Props. The error message I'm receiving is "Parsing error: Unexpected reserved word 'interface'. (3:0)eslint". This project is being developed using next with TypeScript. Er ...

Learn the process of updating database information with AngularJS through a button click

As a newcomer to Angular, I am facing an issue in my mini project. The main goal of the project is to display data from a database. I have successfully set up the view to show current data by making API calls and connecting to the database. However, I am n ...

Changing JSON to XML Request through WSDL

I am currently working with a SOAP web service that accepts XML input and responds with XML data. I now have a JSON object that mirrors the structure of the XML request. How can I convert this JSON object into XML format in order to send it as a request ...