Search code examples
asp.net-mvckendo-uikendo-asp.net-mvckendo-datavizkendo-datasource

Kendo UI Chart - Updating datasource after databound


I have some actions that need to be executed during/after databinding of my charts.

One of the things is that I'm adding missing categories (months). My problem is that if I add those missing values to the datasource, it triggers the databound event again.

Is there a better way to do this?

@(Html.Kendo().Chart<MyModel>()
    .Name("chart")
    .DataSource(ds => ds.Read(read => read.Action("GetData", "Home")))
    .CategoryAxis(a => a.Date().Categories(c => c.Date))
    .ValueAxis(v => v.Numeric().Min(0).Max(100))
    .Series(series => series.Column(d => d.Value))
    .Events(e => e.DataBound("dataBound"))
)

function dataBound(e) {
    var chart = e.sender;
    var today = new Date(); 
    // Add current month to chart
    chart.dataSource.add({
        CategoryDate: today,
        Value: 0
    });
}

Solution

  • Every time data inside DataSource is added, modified or deleted DataSource will trigger event Change, and every widget which has DataSource will trigger event DataBound after DataSource is changed.

    Therefore your DataBound event is triggered twice, whereas your chart using remote service to Read its data, internally there are 2 events which will be trigger to achieve it. Event RequestStart and RequestEnd will be called, so I suggest you add your missing category inside the datasource RequestEnd event.

    Inside the RequestEnd event you can modify its response data, you could debug it to see the full structure of this response; normally it will have the Data property and this is the property that you need to change.

    Sample Code

    @(Html.Kendo().Chart<MyModel>()
        .Name("chart")
        .DataSource(ds => ds.Read(read => read.Action("GetData", "Home"))
                            .Events(evt => evt.RequestEnd("onChartDsRequestEnd")))
        .CategoryAxis(a => a.Date().Categories(c => c.Date))
        .ValueAxis(v => v.Numeric().Min(0).Max(100))
        .Series(series => series.Column(d => d.Value))
        .Events(e => e.DataBound("dataBound"))
    )
    
    function onChartDsRequestEnd(e) {
        // data you should modify before its being placed as datasource's data
        var responseData = e.response;
        responseData.push({.......});
    }
    

    Datasource RequestEnd Documentation