[Chartjs]-How to pass model object to javascript function in asp.net Core

5๐Ÿ‘

โœ…

I have solved this problem!

Solution:

Model:

public class SalesViewModel
    {
        public string salesdate { get; set; }
        public int salesprice { get; set; }
    }

Data:

public class SalesContext
    {
        public string ConnectionString { get; set; }

        public SalesContext(string connectionString)
        {
            this.ConnectionString = connectionString;
        }
        public SalesContext()
        {          
        }

        public List<SalesViewModel> GetAllData()
        {
            List<SalesViewModel> list = new List<SalesViewModel>();
            list.Add(new SalesViewModel() { salesdate = "1", salesprice = 3 });
            list.Add(new SalesViewModel() { salesdate = "2", salesprice = 6 });
            list.Add(new SalesViewModel() { salesdate = "3", salesprice = 7 });
            list.Add(new SalesViewModel() { salesdate = "4", salesprice = 2 });
            list.Add(new SalesViewModel() { salesdate = "5", salesprice = 1 });

            return list;
        }
    }

Controller:

using Newtonsoft.Json;
public IActionResult Chart()
        {
            SalesContext sc = new SalesContext();
            string json = JsonConvert.SerializeObject(sc.GetAllData());
            //ViewData["chart"] = json;
            ViewBag.Sales = json;
            return View(sc.GetAllData());
        }

View:

document.getElementById('addData').addEventListener('click', function() {
            if (config.data.datasets.length > 0) {
                var salesdata = @Html.Raw(ViewBag.Sales);
                config.data.datasets.forEach(function(dataset) {
                        for (var i = 0; i < salesdata.length; i++) {
                            var month = MONTHS[config.data.labels.length % MONTHS.length];
                            config.data.labels.push(month);
                            dataset.data.push(salesdata[i].salesprice);
                        }
                });

                window.myLine.update();
            }
        });

use var salesdata = @Html.Raw(ViewBag.Sales) to get data from controller!

use salesdata[i].salesprice to push data to the dataset!

Thanks!

Leave a comment