Convert ViewBag into a JSON array in order to create a bar chart in a .NET MVC application

I am struggling to convert ViewBag into a Json array in order to create a chart within the .Net MVC framework. Despite attempting to parse the Json data based on solutions from previous queries, the chart is not displaying anything. Here is my code:

Controller

public ActionResult RimChart()
{
    List<RimCalcs> listOfCategories = null;

    Connectors aConn = Connectors.GetInstance();
    listOfCategories = aConn.GetRimCalc();
    var dates = listOfCategories.Select(x => x.Date);
    var profits = listOfCategories.Select(y => y.Rprofit);

    ViewBag.Date = dates;
    ViewBag.profit = profits;

    return View();

}

Razor View

<!DOCTYPE HTML>
  <html>
  <head>
  <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
   <script type="text/javascript">

    window.onload = function () {
        var chart = new CanvasJS.Chart("chartContainer", {
            title: {
                text: "My First Chart in CanvasJS"
            },
            data: [
                {
                    // Change type to "doughnut", "line", "splineArea", etc.
                    type: "column",
                    dataPoints: [
                        { label: JSON.parse('@Html.Raw(ViewBag.profit)'), y: JSON.parse('@Html.Raw(ViewBag.Date)') },

                    ]
                }
            ]
        });
        chart.render();
    }
</script>
</head>
 <body>
 <div id="chartContainer" style="height: 300px; width: 100%;"></div>
 </body>
 </html>

Answer №1

Updated Instead of directly parsing, consider serializing first in order to improve efficiency.

@{
        var profit = JsonConvert.SerializeObject(ViewBag.profit);
        var date = JsonConvert.SerializeObject(ViewBag.Date);
}
 window.onload = function () {

        var chart = new CanvasJS.Chart("chartContainer", {
            title: {
                text: "Creating My First Chart Using CanvasJS"
            },
            data: [
                {
                    // Change type to "doughnut", "line", "splineArea", etc.
                    type: "column",
                    dataPoints: [
                        { label: JSON.parse('@Html.Raw(profit)'), y: JSON.parse('@Html.Raw(date)') },

                    ]
                }
            ]
        });
        chart.render();
    }

You can also choose to Serialize directly within the controller

public  ActionResult RimChart()
    {
        List<RimCalcs> listOfCategories = null;

        Connectors aConn = Connectors.GetInstance();
        listOfCategories = aConn.GetRimCalc();
        var dates = listOfCategories.Select(x => x.Date);
        var profits = listOfCategories.Select(y => y.Rprofit);

        ViewBag.Date = JsonConvert.SerializeObject(dates);
        ViewBag.profit = JsonConvert.SerializeObject(profits);

        return View();

    }

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

Performing an ASync call to the GetData routine in MongoClient using NodeJS

Combining code snippets from https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp and https://stackoverflow.com/questions/49982058/how-to-call-an-async-function#:~:text=Putting%20the%20async%20keyword%20before,a%20promise%20to%20be%20resolved. Upon ob ...

Tips for displaying user data from a mongodb database on a webpage, making edits to the information, and then saving the updated data

I have a website where users can register, log in, and update their profile information. However, I am facing an issue where only the data of the first user in the database table is being retrieved. How can I get the data of the currently logged-in user? ...

What is the best way to retrieve the element at the current cursor position inside an iframe

I'm currently working on a script that is intended to retrieve the element positioned at the cursor's location within an iframe. The code I am attempting to implement should be able to identify the deepest child element at the cursor's posit ...

Creating linear overlays in Tailwind CSS can be achieved by utilizing the `bg-gradient

Is there a way to add a linear background like this using Tailwind CSS without configuring it in tailwind.config.js? The image will be fetched from the backend, so I need the linear effect on the image from bottom to top with a soft background. Here are ...

A guide on extracting the HTTP request body in Resteasy and Wildfly 8.2

Is there a way to capture and display the HTTP request and response bodies in JSON format in Resteasy on WildFly 8.2? I came across this solution Dump HTTP requests in WildFly 8, but it only seems to show headers. I am specifically interested in viewing ...

The Ajax validation form mistakenly redirects the echoes to a different page instead of the intended page for displaying the output

I am currently working on creating an ajax-form to validate the client-side server of my sign-up form. My goal is to have error messages displayed on the same page where they are triggered, without loading a separate page. Below is the code from my (sign ...

AngularJS powered edit button for Laravel route parameter

I have a data list that needs to be edited using an edit button. When clicking the edit button, I need to send the ID to a Laravel controller in order to fetch the corresponding data. The initial listing was created using Angular JS. <a class="btn" hr ...

Modifying the 'child' node within a JSON object

Exploring the implementation of d3s Collapsible tree using a custom node hierarchy. My dataset structure deviates from the norm, for example: http://jsfiddle.net/Nszmg/2/ var flare = { "Name": "Example", "members": [ { "BName":"Ja", ...

Is there a way to choose multiple dropdown items that share the same header?

Utilizing the Fluent UI React Northstar Dropdown component in my React project, I've encountered an issue with multiple item selection. It seems that when there are several items sharing the same header value, only one can be selected at a time. What ...

Next.js throws an error when trying to access the document object while using React Aria overlays

Recently, I've been diving into Next.js for web development and stumbled upon commerce, a template specifically designed for e-commerce websites using Next.js. While exploring the codebase, I noticed the Sidebar component which leverages React Aria fo ...

What is the best way to create a loop with JSON data?

My challenge is to showcase json data using a loop. I have received the following results, but I am unsure of how to display them with a loop. [ {"latitude":"23.046100780353495","longitude":"72.56860542227514"}, {"latitude":"23.088427701737665"," ...

Searching dynamically using class names with JQuery

I am seeking to create a dynamic search input based on the class names within the span tags. However, I am struggling with displaying the class name that I have identified. My goal is to show the class names that match the entered value in the input on the ...

Utilizing Angular's DomSanitizer to safely bypass security scripts

Exploring the capabilities of Angular's bypassSecurityTrust* functions has been a recent focus of mine. My objective is to have a script tag successfully execute on the current page. However, I keep encountering issues where the content gets sanitized ...

The "Boostrap Confirmation" plugin in JQuery fails to appear upon the second click

After changing the confirmation method from an MVC Action to an Ajax method, I noticed that the confirmation box does not appear when clicking a second time. It seems to have stopped working possibly because the page is no longer being refreshed. How can ...

Converting Dynamo DB stream data into Json format

I need to convert the DDB stream message into a standard JSON format. To achieve this, I am using unmarshalleddata = aws.DynamoDB.Converter.unmarshall(result.NewImage); where result.NewImage is { carrier: { S: 'SPRING' }, partnerTransacti ...

Encountering an ExpressionChangedAfterItHasBeenCheckedError in Angular 6 when selecting an option from a dropdown menu

How can we fix the error mentioned below through code changes? Situation An input dropdown UI is safeguarded against unintentional value changes by a modal. However, triggering an event (such as click or focus) on the dropdown leads to the ExpressionChan ...

Tips for implementing the new useState value in your code

Using DataGrid Material UI, I am facing an issue where the selected row is not being deleted when clicking on the delete button. The problem arises from setting the ID value in the useState hook and encountering asynchronous behavior in deleting the rows. ...

Retain the chosen values even after submitting the form

Consider the following form: <form method="get" action=""> <select name="name"> <option value="a">a</option> <option value="b">b</option> </select> <select name="location"> <opt ...

What sets apart loads and dumps from reading a JSON file?

I've got a basic json file named 'stackoverflow.json" { "firstname": "stack", "lastname": "overflow" } What are the differences between the following two functions: def read_json_file_1(): with open('stackoverfl ...

What is the best way to extract data from the JSON response obtained from the Facebook Graph API in a Node

I am struggling to parse a JSON file in order to extract specific data, particularly the latest picture. How can I achieve this using Node.js and the Facebook Graph API? Below is the snippet of code I currently have: var params = { hostname: ' ...