Converting JSON data from ASP.NET MVC to a Canvas.js chart

Despite my efforts to find a solution by looking through similar posts, I am unable to resolve the issue. Within my asp.net MVC controller, I have a method called public object OfferChart()

List<Det> obj = new List<Det>();

            foreach (DataRow dro in dt.Rows)
            {
                Det def = new Det();
                def.xval = Convert.ToString(dro["Section"]);
                def.yval = Convert.ToDecimal(dro["Percent"]);
                obj.Add(def);
            }
            return Json(obj, JsonRequestBehavior.AllowGet);

The objective is to send the data from obj within a JavaScript object and utilize it as dataPoints for my chart (canvas):

function chartOfferSections() {

var chart = new CanvasJS.Chart("chartOfferSections", {
            theme: "light2", // "light1", "light2", "dark1", "dark2"
            exportEnabled: true,
            animationEnabled: true,
            title: {
                text: "Oferte pe sectoare"
            },
            data: [{
                type: "pie",
                startAngle: 25,
                toolTipContent: "<b>{label}</b>: {y}%",
                showInLegend: "true",
                legendText: "{label}",
                indexLabelFontSize: 16,
                indexLabel: "{label} - {y}%",
                dataPoints: 
                [
                    { y: 25.00, label: "Sectorul 1" },
                    { y: 25.00, label: "Sectorul 2" },
                    { y: 25.00, label: "Sectorul 3" },
                    { y: 25.00, label: "Sectorul 4" }
                ]
            }]
        });
        chart.render();
}

After finding some examples and attempting to implement them, unfortunately, none of them worked.

var dataPts[];
$.ajax({
    cache: false,
    async: false,
    type: "POST",
    dataType: "Json",
    contentType: "application/json; charset=utf-8",
    url: '@Url.Action("OfferChart")',
    data: obj,
    success: function (data) {
        var len = data.d.length;
        for (var i = 0; i < len; i++) {
            dataPts.push({
                label: data.d[i].xval,
                y: data.d[i].yval
            });
        }

Answer №1

Make sure to set your temporary data points to the chart options within your success function:

chart.options.data[0].dataPoints = tempDataPts

After that, don't forget to execute chart.render();

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

What could be causing the absence of console.log output in my Netlify function logs?

I am facing an issue with my Netlify function that is scheduled to run every minute using the @netlify/functions package. The function makes API calls and logs the response, but I cannot see any output from the console.log statement in the Netlify function ...

Include the jquery library and embed a Google Map

Hello, I am using jQuery load to refresh my page every second. The problem arises when I add a Google Map to the page - the map appears and disappears every second. Is there a way to fix this issue? $(document).ready(function(){ <?php if( ...

Animation that slides in from the left using CSS styling

My current project involves creating a slideshow, and while it is mostly working fine, I am facing an issue with the animations. The animation for sliding out works perfectly, but the animation for sliding in from the left doesn't seem to be functioni ...

The v-show directive is not activated by a Vuex commit

I am experimenting with vuex for the first time, and I have come across an issue where a v-show directive is not triggering after a mutation commit on the store. // store.js import Vue from "vue" import Vuex from "vuex" const states = ...

Is it possible for me to create a lineString connecting two points in OpenLayers3?

I need to create a lineString connecting my two given points, such as [-110000, 4600000] and [0, 0]. ...

Using Vanilla JavaScript to Disable a Specific Key Combination on a Web Page

On a completely random English-Wikipedia editing page, there exists a way to add content (for example, "test") and save it using the existing key combination of Alt+Shift+S. My goal is to specifically prevent this action without removing the save button b ...

How can a field in JSON Schema be defined to accept a set of predefined strings as well as arbitrary string values?

Our field is typically an enum of strings, but there are occasions where the enum does not account for all possible cases. Therefore, we provide users with the flexibility to input any other string if it is not included in the enum. This serves as a re ...

React component using Highcharts is displaying categories as numeric values instead of text

Incorporating the highcharts-react package (https://github.com/highcharts/highcharts-react) into my Laravel project has presented a unique challenge. I am attempting to fetch data from my reducer and transform it into a string to populate the categories in ...

How can I make an HTML textbox in C# MVC flash a background color for one second using TextBoxFor?

I'm currently working with MVC and have the following code in my razor view. @Html.TextBoxFor(x => model.DateTimeStamp, new { @readonly = "readonly", @class=ViewBag.IsLatest ? "latest":""}) I want to briefly change the background color of this te ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

Unexpected behavior observed in the Python minifier Slimit

Attempting to decrease the size of some JavaScript code using the 'slimit' package in Python. import slimit slimit.minify('[1,2,3,4,5,6,7,8]') The above snippet executes without issue and outputs '[1,2,3,4,5,6,7,8]' import ...

Sharing JSON data with public/javascripts/X.js in Node/Express: A beginner's guide

Currently facing a challenge with my Express project. Take a look at https://github.com/MoreeZ/help1 and examine ./public/javascripts/budget.js. My goal is to swap the incomeData object to read data from ./incomedata.json I attempted passing it through th ...

Angular: Utilizing Nested ng-repeat Alongside groupBy Feature on Initial Page Load or Refresh

With some help, I've made it this far on my project. However, I need to take one more step to achieve my goal. I want to group data based on an attribute that is currently passed through an ng-click action. Is there a way to automatically do this on p ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

Embracing the power of dynamic imports in Next.js 10 with SDK integration for

I attempted to dynamically import the TRTC SDK using Next.js 10: const TRTC = dynamic(() => import('trtc-js-sdk').then((module) => module.NamedExport), { ssr: false }); However, I encountered an error stating "TRTC.createClient is not a co ...

Retrieving the Vue component object while inside the FullCalendar object initialized within the component

When using Full Calendar with VueJS, I ran into a problem where I needed to open a custom modal when clicking on a time slot in the calendar. The issue was that I couldn't call a function outside of the Full Calendar object to handle this. This is bec ...

Image caption dynamically updated to match thumbnail caption using jQuery upon click event

My goal is to dynamically load the data-caption of thumbnail images when clicked, and then update the main image's data-caption when the main image is changed with a thumb image. I am currently struggling to make the data-caption update along with the ...

Checkbox malfunctioning when trying to add values after being checked

I have successfully completed a calculation system project using JavaScript. Everything works well, the calculations are accurate and taxes are included properly. However, I am facing an issue where the tax is not being included when I click on the checkbo ...

The state returned by React Redux does not meet the expected results

I recently implemented a like function on the backend using Node and MongoDB. This function successfully returns the post with an updated likes counter, which I tested using Postman. The post object contains properties such as likes, _id, by, createdAt, an ...

Learn the process of adding a key and value into an array using Angular

I need to filter data based on the number of rows and columns provided by the user. After reading an excel file, I extract the data in the controller: https://i.sstatic.net/vPpxL.png These are the column headers retrieved after the user entered 5 as the ...