Tips on incorporating live data into charts using MVC?

Recently I started working with ASP.NET MVC on my own project and have encountered some difficulties. One particular challenge I am facing is how to create a line chart using data from a database.

Let me explain the issue in more detail:

Within my database, I have a table that stores information about different metals. When I select a specific metal, I want to display a chart illustrating its price trend over time.

For instance, if I select Copper:

The controller for handling this functionality is PricePoint; but which action should I trigger here?

<a href="@Url.Action("DrawChart", "PricePoint", new { id = item.ID })">@Html.DisplayFor(modelItem => item.name)</a>

By calling the DrawChart Action in the PricePoint controller:

public ActionResult DrawChart()
{
    return View();
}

In the same controller, I have also set up an action to retrieve data from the database, encode it as JSON, and pass it back:

 public ActionResult Statistics(int ?id) {
        // fetching data from database to stats 
        return Json(stats,JsonRequestBehavior.AllowGet);
    }

This relates to my view page where I intend to showcase the chart, within the DrawChart.cshtml file.

<script type="text/javascript">
    $.get('@Url.Action("Statistics")', function(result){
        new Morris.Line({
            element: 'myfirstchart',
            data: [
             result
            ],
            xkey: 'year',
            ykeys: ['value'],
            labels: ['Value']
        });
    });
</script>

My understanding is that upon clicking on a metal, the DrawChart action will render the DrawChart.cshtml view, following which the JavaScript function will invoke the Statistics method to populate data for the chart. Am I on the right track?

However, when accessing the URL http://localhost:50101/PricePoint/DrawChart, I end up with a blank page. On the other hand, requesting http://localhost:50101/PricePoint/Statistics displays json data retrieved from the database.

I'm unsure what could be causing this issue. Interestingly, when I manually input sample data in the script like so:

data: [
      { year: '2008', value: 20 },
      { year: '2009', value: 10 },
      { year: '2010', value: 5 },
      { year: '2011', value: 5 },
      { year: '2012', value: 20 }
    ],

The line chart appears as expected. Apologies for any language barriers, and I appreciate any assistance you can provide in addressing this matter.

Answer №1

I experimented with it and successfully displayed the chart. Here are a few things to consider that may be causing issues:

1) Ensure that your call to

$.get('@Url.Action("Statistics")'
includes an id parameter, even though you have declared it in your action
public ActionResult Statistics(int ?id)
. It's possible that not passing an id is affecting the logic of your database retrieval.

2) I noticed that the link to the DrawChart action included new { id = item.ID }, but this parameter is not captured server-side since the DrawChart action is missing the parameter specification:

public ActionResult DrawChart(id)
. This discrepancy may impact the functionality.

3) Pay attention to what you are returning from the MVC action. The stats object in

return Json(stats,JsonRequestBehavior.AllowGet);
should be a C# array containing value and year properties for each object. Check that your JSON return follows this structure.

If you need to return a string instead of a serialized collection, use something like:

return Content(dataString, "application/json");

4) Make sure that the JSON returned contains properties named year and value, matching the declaration in your Morris object on the xkey and ykey values. JavaScript tends to use lowercase while .NET typically uses uppercase for property names.

Conclusion: I resolved the issue by updating my Statistics method as follows:

 public ActionResult Statistics(int ?id) {
       var data = new[] {new Entry() {value = 20, year = 2008}, new Entry() {value = 10, year = 2009}};

            return Json(data,JsonRequestBehavior.AllowGet);
    }

In your Morris initialization code, remove the array brackets from the data declaration to data : result instead of data : [result]

To troubleshoot further, inspect the output of your Statistics method using Chrome Developer Tools or similar tools. Ensure that the data format matches Morris' expectations to avoid errors.

Remember to wrap the Morris init code in a $(document).ready() function for optimal performance.

Answer №2

When transmitting data (including values and dates) manually from a function, everything works fine. The JSON file is correctly populated, and the chart is displayed as expected. However, when the data is sent from the database, although the JSON file seems to be populated, the chart does not appear.

Below is the code snippet:

public class YearlyStat
    {
        public string year { get; set; }
        public double value { get; set; }
    }

public ActionResult Statistics(int? id)
    {
        var items = from item in db.pricepoints
                    where (item.commodityID == id)
                    select item;

        var stats = new List<YearlyStat>();

        foreach (var item in items)
        {
            stats.Add(new YearlyStat
            {
                year = item.date_of_price.ToShortDateString(),
                value = item.value
            });

        }

        return Json(stats, JsonRequestBehavior.AllowGet);
    }

In both cases, the types being used are string and double...

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

NodeJS domain error handling failing to catch ReferenceError exceptions

I'm currently facing some challenges with domains in NodeJS. I've set up middleware functions to wrap every call in my web application within a domain in order to capture errors, process them, and return informative error messages. While this se ...

Highcharts: Show tooltip above all elements

Is there a way to configure tooltip display above all elements? I want to define specific coordinates so that the tooltip remains open even if it is covering the chart, and only closes when interacting with the top block. Screenshot 1 Screenshot 2 For e ...

Tips for extracting data from JSON values

My JSON Data Display let foodData = [{ meal_com_id: "1", name_company: "PeryCap", image: "https://shopgo.in/upload/1545849409-1518284057-Untitled-nn1.png", status: "1", description: "sdvaebfvhjaebfber itnwiuore tg5ykrgt wiretgi34 tgi3rgt ...

Tips for breaking down a collection of objects and nested arrays into distinct arrays containing individual pieces of data

I have a list of objects structured like this: [ { alert_count: 3, alert_level: {value: 0, label: "ignore"}, count_dates: (3) ["2021-04-21T14:36:02.446Z", "2021-04-21T14:36:12.039Z", "2021-04-21T14:37:04.495Z"], sound_type: {_id: "606331d ...

Is it feasible to import an array of tuples from a JSON file?

How can I load an array of tuples from a JSON file? I attempted the following approach but it was unsuccessful. The contents of my json file are as follows: { "broken" : [(1,1), (1,2), (2,2), (3,1)]} My current method involves using the loadsjsonfromb ...

Ways to store session storage item in a variable

I am looking for a way to save items from local storage using C# (via JS, as there doesn't seem to be a solution with pure C#). I quickly tried the following code: public string token; string storageToken = "localStorage.getItem('token')"; ...

What's the best way to vertically center a div with a 100% width and a set padding-bottom on the screen?

I am struggling with positioning the following div on my webpage. .div { width:100%; padding-bottom:20%; background-color:blue; } <div class="div"></div> I have been searching for a solution to vertically center this responsive div on my web ...

Why does my Visual Studio Code always display "building" when I launch an extension?

https://code.visualstudio.com/api/get-started/your-first-extension I followed a tutorial to create a hello world extension. Why does my VSCode always display 'building' when I run the extension? Executing task: npm run watch < [email p ...

Tomickigrzegorz Script Finder Predictive Search

Hey there, I recently tried out the autocomplete script created by tomickigrzegorz. Check it out here! It's been working smoothly for me, but I'm facing an issue with external link tags like https//google.com not functioning properly. Here is ...

Manipulating the DOM by linking to a div and using JSON information for opening and closing

I have retrieved data from a JSON file and displayed it as a link. I am looking to implement functionality that allows me to hide and show a div when the link is clicked. Below is the code I'm currently using: $(document).ready(function() { $ ...

Determine the most recent API response and disregard any outdated responses from previous calls

I am currently working on a search page where the user can input text into a search box. With each character they enter, an ajax call is made to update the UI. However, I am facing an issue in determining the response from the last API call. For example, i ...

How to insert a JSON object into a nested array using JavaScript

I am currently facing an issue with adding a JSON object based on specific conditions to an array, which is then used to create a WINJSList. The problem arises when I try to access the elements of the list or array after using the array.push method. My goa ...

Troubleshooting JSON parsing issues in PHP

In reference to the discussion at: , where suggestions mainly revolved around JavaScript. Is there a specific function in PHP that can be utilized to address the issue described below and ensure that the output is valid JSON? Please note that using front ...

Guide to adding a new table with JSON information to an Azure SQL Database using an API

I am currently facing an issue in our data processing using Azure SQL Database. We are looking to automate the process of loading data from our accounting platforms through API, instead of manually importing it every time. (API Documentation Links: , ) M ...

Managing the response from a variable returned by jQuery's .load method

I am facing an issue with my code. I am using jQuery post to validate whether the name of the filter is available for use. $.post('check-username.php', $("#myform").serialize(), function(data) { alert(data); }); When I use the alert to disp ...

What is the best way to execute a loop while asynchronously calling a service in .NET Core 6 and ensuring that it waits for the result at the end

Seeking ways to enhance performance and minimize data display delay for users. The job involves retrieving data from multiple sources, processing it sequentially which is time-consuming. Looking for suggestions on boosting performance by making asynchrono ...

The feature of Jackson that allows for polymorphic type conversion will remove the property once it has

I'm encountering an issue with Jackson where the property used for discriminating subtypes is being deleted at the end of the parsing process. Despite successfully parsing the JSON payload to the correct subtype, I find that the distinguishing propert ...

Move the window positioning from the lower section to the center

Is there a way to make images appear when they are at 75% or in the middle of the window instead of waiting for them to be fully in view? How can I achieve this? $(window).on("load",function() { function fade(pageLoad) { var min = 0; ...

Setting up Authorization for FETCH requests in NEXT.js using .env.local

`export default function reservations() { let [reservationStock, setReservationStock] = useState([]); useEffect(() => { fetch(url, { headers: new Headers({ Authorization: "MyBasic Credentials", " ...

Differences between applying addClass(undefined) and addClass(null)

At times, it crosses my mind to include a class in a chain, depending on certain conditions. What would be the most fitting semantic value to add no class? For instance: $(".element").performAction().addClass(condition ? "special-class" : undefined).perf ...