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.