This is a migrated thread and some comments may be shown as answers.

How to refresh Series

3 Answers 1120 Views
Chart
This is a migrated thread and some comments may be shown as answers.
Michel
Top achievements
Rank 1
Michel asked on 21 Jul 2017, 02:55 PM

I need to refresh my PieChart using calculation made in my controller using a DatePicker.

Despite the update of the Viewbag used for the series in my controller, It seems that the series are not updated when refreshing the Chart.

Any suggestions ?

MyView :

@(Html.Kendo().DatePicker()
          .Name("startDatepicker")
          .Value(DateTime.Now.ToShortDateString())
          .Events(e =>
          {
            e.Change("onStartDateChange");
          }))
@(Html.Kendo().Chart()
      .Name("chartWorkDuration")
      .Title(title => title.Text("Working time - Total : " +
                                 ViewBag.TotalWorkDuration.ToString() + "h")
                            .Position(ChartTitlePosition.Bottom))
      .ChartArea(chart => chart.Background("transparent"))
      .Series(series => series.Pie(ViewBag.arWorkDuration)
              .Padding(0)
      )
      .Tooltip(tooltip => tooltip
          .Visible(true)
          .Format("{0:N0}")
      )
)
<script>
  function onStartDateChange() {
    var startDate = $("#startDatepicker").data("kendoDatePicker").value().toDateString();
    $.ajax({
      url: 'PlanningGraph/RefreshGraph',
      cache:false,
      data: {
        startDate: startDate
      },
      success: function (xhr, textStatus) {
        $("#chartWorkDuration").data("kendoChart").refresh();
      }
    });
    });
  }
</script>

My Controller

// Creation of my viewmodel elements
....
      var workDuration = graphElementViewModels.Select(w => new
        {
        category = w.strCategory,
        value = w.dblValue,
        color = w.strColor
        });
ViewData["arWorkDuration"] = workDuration;

 

3 Answers, 1 is accepted

Sort by
0
Stefan
Telerik team
answered on 25 Jul 2017, 06:52 AM
Hello Michel,

Thank you for the provided code.

The described result is expected because the refresh method will only redraw the Chart using the current data and it will not set a new one.

In this scenario, I can suggest the two approaches. Using a Kendo UI DataSource for the Chart which will allow redrawing the data by calling the read method of the Chart. The other option will be to manually set the new data to the Chart series and then refresh it.

More information for both implementations can be found in the following forum thread:

http://www.telerik.com/forums/best-way-to-draw-chart-with-dynamically-changing-data

http://demos.telerik.com/aspnet-mvc/pie-charts/remote-data-binding

I hope that this will help to achieve the desired result.

Regards,
Stefan
Progress Telerik
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data (charts) and form elements.
0
Michel
Top achievements
Rank 1
answered on 25 Jul 2017, 12:57 PM

Hi Stefan,

Thank you for your reply.

I have modified my code using a ViewModel because I suspect that perhaps the use of the ViewBag could bring unexpected result.

Here is my code but as you will notice I did not find a way to set the series with the color inside my ViewModel as KendoChart seem to accept only two parameters. So I have used the SeriesColors property instead to set the colors (not so useful that if color could be inside the ViewModel). Am I Right ?

My View (including stuff to populate grandTotal in the title):

....
   @(Html.Kendo().DatePicker()
              .Name("startDatepicker")
              .Value(DateTime.Now.ToShortDateString())
              .Events(e =>
              {
                e.Change("onStartDateChange");
              }))
...
    @(Html.Kendo().Chart<GraphElementViewModel>()
              .Name("chartWorkDuration")
              .Title(title => title.Text("Workin time in hour")
                                    .Position(ChartTitlePosition.Bottom))
              .ChartArea(chart => chart.Background("transparent"))
            .SeriesColors((String[])ViewData["arColor"])
            .DataSource(ds =>
            {
              ds.Read(read => read.Action("GetWorkDuration", "PlanningGraph").Data("GetStartDate"));
            }
            )
            .Series(series => series.Pie(
            model => model.dblValue, model => model.strCategory)
            )
            .Tooltip(tooltip => tooltip
                .Visible(true)
                            .Format("{0:N0}"))
          .Events(events => events.DataBound("onChartWorkDurationDataBound")
            )
    )
<script>
  function GetStartDate() {
    var startDate = $("#startDatepicker").data("kendoDatePicker").value().toDateString();
    return { startDate: startDate };
  }
 
  function onStartDateChange() {
    $("#chartWorkDuration").data("kendoChart").dataSource.read();
  }
 
  function onChartWorkDurationDataBound(e) {
    var pieChart = $("#chartWorkDuration").data("kendoChart");
    var grandTotal = 0;
    var chartSeries = pieChart.options.series;
    for (var i = 0; i < chartSeries.length; i++) {
      var chartSeriesData = chartSeries[i].data;
      //Sum of values
      for (var j = 0; j < chartSeriesData.length; j++) {
        var currDataItem = chartSeriesData[j];
        grandTotal += currDataItem.dblValue;
      }
    }
    pieChart.options.title.text = "Working time in hour - Total : " + grandTotal.toString() + " h";
  }
</script>

My controller :

...
    public String[] arColorList = new String[]
      {
    "#00C0C0",
    "#009DC0",
    "#0080C0",
     };
 
...
 
    public IActionResult Index()
      {
      ViewData["arColor"] = arColorList;
      return View();
      }
...
    [HttpPost]
    public ActionResult GetWorkDuration(string startDate)
 
      {
// Sample stuff - the running version read data from SQL server
      List<GraphElementViewModel> graphViewModels;
       GraphElementViewModel curGraphElementViewModel = new GraphElementViewModel();
       curGraphElementViewModel.strCategory = "Category 1";
       curGraphElementViewModel.dblValue = 30.0;
       graphViewModels.Add(curGraphElementViewModel);
       curGraphElementViewModel = new GraphElementViewModel();
       curGraphElementViewModel.strCategory = "Category 2";
       curGraphElementViewModel.dblValue = 30.0;
       graphViewModels.Add(curGraphElementViewModel);
       curGraphElementViewModel = new GraphElementViewModel();
       curGraphElementViewModel.strCategory = "Category 3";
       curGraphElementViewModel.dblValue = 40.0;
       graphViewModels.Add(curGraphElementViewModel);
      return Json(graphViewModels);
      }
...

My View Model

...
  public class GraphElementViewModel
    {
    public string strCategory { get; set; }
    public double dblValue { get; set; }
 
    public GraphElementViewModel()
      {
      strCategory = "";
      dblValue = 0.0;
      }
    }

 

Hope this code can also help other users.

Regards.

 

 

 

0
Stefan
Telerik team
answered on 27 Jul 2017, 06:50 AM
Hello Michel,

I'm glad to hear that the issue is resolved.

Also, the color can be set from a field in the data using the colorField property of the Chart:

http://docs.telerik.com/aspnet-mvc/api/Kendo.Mvc.UI.Fluent/ChartPieSeriesBuilder#methods-ColorField(System.String)

Regards,
Stefan
Progress Telerik
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data (charts) and form elements.
Tags
Chart
Asked by
Michel
Top achievements
Rank 1
Answers by
Stefan
Telerik team
Michel
Top achievements
Rank 1
Share this question
or