Creating an interactive Google line chart in MVC4

I am currently working on a dynamic line chart that needs to be able to adjust the number of lines (Standard, Latest, Earliest, Average) based on the database records. My code structure is similar to this example.

function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Month', 'Standard', 'Latest', 'Earliest', 'Average'],
            ['Original Documents', @Convert.ToDecimal(@Standard[0].ToString()), @Convert.ToDecimal(@Latest[0].ToString()), @Convert.ToDecimal(@Earliest[0].ToString()), @Convert.ToDecimal(@Average[0].ToString())],
            ["Filing of Entries", @Convert.ToDecimal(@Standard[1].ToString()), @Convert.ToDecimal(@Latest[1].ToString()), @Convert.ToDecimal(@Earliest[1].ToString()), @Convert.ToDecimal(@Average[1].ToString())],
            ["Assessment of Duties", @Convert.ToDecimal(@Standard[2].ToString()), @Convert.ToDecimal(@Latest[2].ToString()), @Convert.ToDecimal(@Earliest[2].ToString()), @Convert.ToDecimal(@Average[2].ToString())],
            ["Payment of Duties", @Convert.ToDecimal(@Standard[3].ToString()), @Convert.ToDecimal(@Latest[3].ToString()), @Convert.ToDecimal(@Earliest[3].toString()), Convert.ToDecimal(@Average[3].ToString())],
            ["Releasing", Convert.ToDecimal(@Standard[4].toString()), Convert.ToDecimal(@Latest[4].ToString()), Convert.ToDecimal(@Earliest[4].toString()), Convert.ToDecimal(@Average[4].toString())],
            ["Gate Pass", Convert.ToDecimal(@Standard[5].toString()), Convert.ToDecimal(@Latest[5].toString()), Convert.ToDecimal(@Earliest[5].toString()), Convert.ToDecimal(@Average[5].toString())],
            ["Delivery", Convert.ToDecimal(@Standard[6].toString()), Convert.ToDecimal(@Latest[6].toString()), Convert.ToDecimal(@Earliest[6].toString()), Convert.ToDecimal(@Average[6].toString())]
        ]);

https://i.stack.imgur.com/tiOBw.png

Answer №1

Consider modifying your function to accept a Json array in the following format:

function drawChart(jsonData) {
    var array = JSON.parse(jsonData);
    var data = google.visualization.arrayToDataTable(array);
    var options = {
        hAxis: {
          title: 'X-Axis Legend'
        },
        vAxis: {
          title: 'Y-Axis Legend'
        }
    };
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}

The data should be structured in a row-per-x-position, column-per-line format as outlined in the documentation:

Rows: Each row in the table represents a set of data points with the same x-axis location.

To populate this Json from your controller method, you can use a loop or other technique to add each new line and its corresponding data dynamically:

var data = new[] {  
    new[] {"Month", "Line1", "Line2", "Line3", "Line4"}, // Add new lines here
    new object[] {"x-label1", 1, 2, 3, 4 }, // Add data points
    new object[] {"x-label2", 11, 12, 13, 14 },
    new object[] {"x-label3", 7, 6, 2, 17 },
    new object[] {"x-label3", 17, 19, 23, 9 },
    new object[] {"x-label3", 12, 4, 11, 18 }
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);

This results in the following Json being generated:

[["Month","Line1","Line2","Line3","Line4"],["x-label1",1,2,3,4],["x-label2",11,12,13,14],["x-label3",7,6,2,17],["x-label3",17,19,23,9],["x-label3",12,4,11,18]]

For a visual representation and implementation example, check out this JSFiddle demonstration.

UPDATE: Below is a sample C# code snippet to convert your line data from row-based to columnar format. Adjust the number of lines as needed and paste the resulting Json into the provided JSFiddle example for visualization:

var numberOfLines = 7; // Specify the number of lines desired.
var xAxisHeadings = new object[] { "NOT USED", "Original Documents", "Filing of Entries", "Assessment of Duties", "Payment of Duties", "Releasing", "Gate Pass", "Delivery" };
var lines = new List<object[]>();
lines.Add(xAxisHeadings);

// Generate data for each line based on multiples of the line number
for (int i=0; i<numberOfLines; i++)
{
    lines.Add(new object[] { "L" + i, 1 * (i+1), 2 * (i+1), 3 * (i+1), 4 * (i+1), 5 * (i+1), 6 * (i+1), 7 * (i+1) });
}

var answer = new List<object>{};
for (int i=0; i<lines.Count; i++)
{
    var x = lines.Select(a => a[i]).ToArray();
    answer.Add(x);
}

var json = Newtonsoft.Json.JsonConvert.SerializeObject(answer);

The resulting Json is as follows:

[["NOT USED","L0","L1","L2","L3","L4","L5","L6"],["Original Documents",1,2,3,4,5,6,7],["Filing of Entries",2,4,6,8,10,12,14],["Assessment of Duties",3,6,9,12,15,18,21],["Payment of Duties",4,8,12,16,20,24,28],["Releasing",5,10,15,20,25,30,35],["Gate Pass",6,12,18,24,30,36,42],["Delivery",7,14,21,28,35,42,49]]

By integrating this into the existing JSFiddle example, you can visualize the updated data with this revised JSFiddle demo.

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

Effortlessly glide to a specific div ID upon page load using the URL address

One way to implement smooth scrolling to an anchor on page load is by using jQuery. Here's an example code snippet: $(function(){ $('html, body').animate({ scrollTop: $( $('#anchor1').attr('href') ).offset(). ...

jQuery Autocomplete with Link Options

Can anyone help me with creating a search function for my charity's internal website? I've managed to get it partially working, but I'm struggling to make the results link to the right places. Below is the code I have so far, including test ...

"Enhance your Magento store with the ability to showcase multiple configurable products on the category page, even when dropdown values are not

As I work on adding multiple configurable products to a category list page in Magento 1.7.2, I am facing some challenges due to using the Organic Internet SCP extension and EM Gala Colorswatches. While following tutorials from various sources like Inchoo a ...

Tips for retrieving javascript-generated HTML content

Currently, I'm attempting to retrieve article headlines from the NY Times website. Upon inspection, it appears that the HTML is being generated by Javascript since it's only visible when using the 'inspect element' feature in Firefox. ...

Using radio buttons to toggle the visibility of a div element within a WordPress website

I am currently working on creating a WordPress page using the custom page tool in the admin interface. My goal is to have 3 radio buttons, with 2 visible and 1 hidden. The hidden button should be automatically checked to display the correct div (although ...

What is the correct way to use assert in Selenium to verify if a newly added item has been successfully added to the system?

I recently encountered an issue with my form used to add new users. The assert statement is failing because it cannot find the added user, even though I can visually confirm that the user was successfully added when running the program manually. This exact ...

linking to a page that shows the user's chosen option from a dropdown menu

One of the challenges I encountered was creating a feature that allows users to share a specific selection from multiple dropdown lists on a page. Essentially, my goal was to enable users to send a link that would direct others to the same page with the ex ...

Communicating PHP variables with JavaScript through AJAX in a chat application

Hello there! I am currently in the process of developing a chat application for my website that includes user registration and login. My backend server is built using NodeJS to leverage SocketIO capabilities. Within my index.php file, I have implemented ...

Showcasing a JSON file in the interface using $http in AngularJS

I am a beginner in angularjs (and programming). I am attempting to showcase a json file on my view (home.html) using $http and ngRepeat, but unfortunately, it is not working as expected. Upon inspecting the angular responses, I noticed that there are numer ...

Activate the last div within the identical class

When I make an ajax call to fetch more results and append them to the existing ones on the same page, I want to display a scrolling spinner while the contents are being fetched. I am adding a div at the bottom of the fetched results like this: <div cla ...

Incorporate custom JavaScript files that contain classes within a Vue component

i am encountering an issue with a js file that contains classes with functions. i have a vue component and i want to create an instance of that class within it. (when directly copying the file into my <script> tag, everything works smoothly) myfile. ...

Create a new visual masterpiece using Canvas by repurposing an

I am currently working on the following code snippet; export default async function draw(elRef : RefObject<HTMLCanvasElement>, tileData : TileProps) { const canvas = elRef.current!; const ctx = canvas.getContext('2d')!; ctx.clearRect( ...

Angular directive has issues with $compile functionality

This Angular directive automatically appends a new HTML item to the page every time my model changes: app.directive('helloWorld', function($compile) { return { restrict: 'AE', replace: true, scope:{ ...

Utilize JQuery to extract data from JSON and populate form inputs

Working on a web project where I need to make use of AJAX and JQuery to update certain fields without refreshing the entire page. After testing, everything seemed to work fine with dummy data. However, when trying to parse actual JSON data generated from M ...

Loading jQuery on Ajax can be a challenge

I am currently faced with the challenge of working on code that I did not write myself or fully comprehend. The page utilizes AJAX to dynamically load content, and my goal is to manipulate this content. However, when I try to apply jQuery to the dynamic el ...

Swap out internal Wordpress hyperlinks for Next.js Link Component

Currently, I am working on a project where I'm using WordPress as a headless CMS with GraphQL for my Next.js app. Most aspects are running smoothly except for the internal content links within articles that are fetched through the WP API. These links ...

Transform CI_Model into JSON format and then forward it to AJAX communication

How can I convert an object to JSON using json_encode and then send this JSON to AJAX as a response? Custom Code Example : <?php class CustomResponse extends CI_Model { private $status; private $data; public function __construct() { ...

Elevate the element from the choice API to the organization API using this.$parent

I recently developed a Vue 3 component called "Tab" using the option API. Here is the code: export default { name: "Tab", props: { name: {required: true}, iconClass: {required: true}, selected: {default: false} }, da ...

The style properties of Material UI ButtonGroup are not being properly applied

Within a Grid container, I have a Product image with associated buttons. The visibility of these buttons is determined by specific state variables. If the product quantity is 0, an "ADD TO CART" button is displayed; otherwise, a Button Group with '-&a ...

Issue with HTML5 Canvas y-axis dimensions

I am attempting to create a basic animated HTML canvas with a moving block controlled by WASD keys. I encountered an issue where drawing a 5x5 rectangle appeared to be 5x10 on the canvas. Upon inspecting my code and logging the position of the element, I d ...