Chartjs-How to seprate label and total value using array and pass to view

0👍

You can create a ViewModel class that will contain both the labels and the data:

public class ChartJsViewModel {
    public List<object> unitdata {get; set;}
    public List<object> labels {get; set;}
}

And use it like so:

[HttpPost]
public JsonResult MemberData()
{

    List<object> unitdata = new List<object>();
    List<object> labels = new List<object>();

    // Populate the unitdata and labels from your database
    .....

    ChartJsViewModel chartModel = new ChartJsViewModel {
         unitdata = unitdata,
         labels = labels
     };

    return Json(chartModel);
}

You can then deserialize the chartModel Json in the view page.

On the view can you have something like:

@model namespace.folder.ChartJsModelView

<div>
Chart JS Components
</div>

 <script>
var myLabels = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(@Model.labels));
var myData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(@Model.unitdata));

/* Other chartjs script functions */
......
</script>

Leave a comment