Home forums Using CanvasJS Dynamic chart from SQL Server in MVC Reply To: Dynamic chart from SQL Server in MVC

#14210

Arqu07
Member

My answer was deleted but I’ve received a reply on mail. I was trying do something similar like on this page but my chart still doesn’t update changes.
Here my model:

namespace ChartMVC.Models
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    
    [DataContract]
    public partial class Table
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public Nullable<decimal> Value1 { get; set; }
        [DataMember]
        public Nullable<decimal> Value2 { get; set; }
        [DataMember]
        public Nullable<System.DateTime> Date { get; set; }
    }
}

Controller:

 private BazaDEntities _db = new BazaDEntities();
        public ActionResult About()
        {
            try
            {
                ViewBag.DataPoints = JsonConvert.SerializeObject(_db.Table.ToList(), _jsonSetting);

                return View();
            }
            catch (System.Data.Entity.Core.EntityException)
            {
                return View("Error");
            }
            catch (System.Data.SqlClient.SqlException)
            {
                return View("Error");
            }
        }
        JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };

View:

<div id="chartContainer"></div>

<script type="text/javascript">
	var result = @Html.Raw(ViewBag.DataPoints);
	var dataPoints =[];
	for(var i = 0; i < result.length; i++){
		dataPoints.push({label:result[i].Date, y:result[i].Value2});
	}

	$(function () {
		var chart = new CanvasJS.Chart("chartContainer", {
			theme: "theme2",
			zoomEnabled: true,
			animationEnabled: true,
			title: {
				text: "Line Chart with Data-Points from DataBase"
			},
		
			data: [
			{
				type: "line",

				dataPoints: dataPoints,
			}
			]
		});
		chart.render();
		var x = i;
		var updateInterval = 1000;
		var updateChart = function () {
		    for(var y=x; y < result.length; y++){
		        dataPoints.push({label:result[y].Date, y:result[y].Value2});
		    }
		    x=y;
		    chart.render();
		};
		setInterval(function () { updateChart() }, updateInterval);

	});
</script>

Any clues what I am doing wrong? Here is my full project