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

dynamic refresh of Bar DataWiz acording to new data

12 Answers 358 Views
Charts
This is a migrated thread and some comments may be shown as answers.
Daniel
Top achievements
Rank 1
Daniel asked on 11 Jan 2013, 10:22 AM
Hello,
i have a dropdown above the chart with products,and in the chart it shows the quantity per several years.
when i change the dropdown,in the change event,i call the jquery function $.Get(/GetProducts",{productID:$("#category").val()})

and in the controller the action:
private ActionResult GetProducts(int? productID)
{
var products=_productSalesRepository.GetAll().Where(x=>x.ProductID==(productID ?? 1));
return Json(result,JsonRequestBehaviour.AllowGet);
}
products are something like [{ProductID:1},{Year:1997},{Quantity:40}],[{ProductID:1},{Year:1998},{Quantity:50}]

but the problem is that the chart doesn't refresh and draw new bars,acording to the new values.I can confirm that, the action is called,and return the new set of data.
How can i do this to work?

Regards,
Daniel

12 Answers, 1 is accepted

Sort by
0
Alexander Valchev
Telerik team
answered on 14 Jan 2013, 05:15 PM
Hello Daniel,

Data format that you posted cannot be loaded from the DataSource. Please return the information in the following format:
[
    {"ProductID":1, "Year":"1997", "Quantity":40},
    {"ProductID":1, "Year":"1998", "Quantity":50}
]

Provided code does not explain how do you change the Chart's data. If you would like to follow the current approach you may replace the data directly through the data method.

Another solution that I recommend is to filter the DataSource. If serverFiltering is set to true you would be able to filter on the server and return the reduced data set via Ajax request. Similar approach is used in this demo.

I hope this will help.

Kind regards,
Alexander Valchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Daniel
Top achievements
Rank 1
answered on 15 Jan 2013, 07:44 AM
Hello Alexander, the example shows exactly my ideea ,but can you show me for MVC?if the Data is get from an MVC Action in a controller.The format of data i was trying to suggest only,that it is in Json format,maybe i made some mistakes in his representation.
Regards
0
Alexander Valchev
Telerik team
answered on 17 Jan 2013, 07:59 AM
Hi Daniel,

I am afraid that you cannot define widgets with shared DataSource using the MVC wrappers. As you can see the demo has only a HTML/JavaScript version.
My recommendation is to initialize the widgets using JavaScript syntax (example) and retrieve the data from MVC controller via Ajax request. I believe that you may find this sample project helpful as it demonstrates how to bind Kendo Grid (JavaScript) to MVC backend.

Regards,
Alexander Valchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Daniel
Top achievements
Rank 1
answered on 17 Jan 2013, 01:25 PM
so each time,the source of the chart is changing,i have to recreate the whole chart(call the function that create the chart) ?
or chart.Redraw() / chart.Refresh() is enough to show the new data after send/receive new data(via ajax)?

Best Regards,
Daniel
0
Alexander Valchev
Telerik team
answered on 21 Jan 2013, 11:48 AM
Hi Daniel,

The Chart will automatically refresh after its DataSource changes.

I am not sure how do you plan to send and receive the new data. Do you use the build-in DataSource transport or separate Ajax request?

  • in case you work with the DataSource transport, all you need to do is to read (or filter) the DataSource.
    var sharableDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "data-service.json",
                dataType: "json"
            }
        }
    });
     
    sharedDataSource.read(); //fetch data from server and refresh the chart
    sharedDataSource.filter(); //filter the dataSource and refresh the chart
  • in case you retrieve the data through external Ajax request, you may hook up to its success event and use the data method to change Chart's data

    $.ajax({
        url: "your-url",
        dataType: "json",
        success: function (response) {
            var data = response.data; //extract the array with data from the server response
            dataSource.data(data); //replace dataSource data and refresh the chart
        }

Regards,
Alexander Valchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Daniel
Top achievements
Rank 1
answered on 21 Jan 2013, 02:05 PM
i have the response using ajax,but
the creation of the chart is with razor like this:

<div class="chart-wrapper">
    @(Html.Kendo().Chart<DomainModelProject.Models.vwSalesQuantityYear>()
        .Name("chart")
        .Title("Sales of")
        .Legend(legend => legend.Position(ChartLegendPosition.Top))
        .DataSource(ds => ds.Read(read => read.Action("GetSalesPerQuantityYear", "Controls")))
               .Series(series =>
               {
                   series.Line(model => model.Quantity).Name("Quantity");

               })
        .CategoryAxis(axis => axis
            .Categories(model => model.Years)
            .Labels(labels => labels.Rotation(-90))
        )
        .ValueAxis(axis => axis.Numeric()
            .Labels(labels => labels.Format("{0:N0}"))
            .MajorUnit(20)
        )
        .Tooltip(tooltip => tooltip
            .Visible(true)
            .Format("{0:N0}")
        )

    )
</div>
also the Dropdownlist is created like this:
@(Html.Kendo().DropDownList()
          .Name("category")
          .OptionLabel("Select a product...")
          .DataTextField("ProductName")
          .DataValueField("ProductID")
          .HtmlAttributes(new { style = "width:200px" })
          .DataSource(source => source.Read("ProductListData", "Controls"))
          .Events(ev => ev.Change("change"))

and in the script section...
function change() {
        $.get("/Controls/GetSalesPerQuantityYear", { productID: $("#category").val() }, function (e) {

            var chart = $("#chart").data("kendoChart");
            chart.dataSource.data(e);
            // refreshes the chart
            chart.redraw();
            chart.refresh();
          
        });
in the variable e,i have an array of values just like you showed me in the previous reply.
with firebug i can reproduce to you a fragment
[Object { ID=
27
, ProductID=
10
, Years=
1996
, more...}
, Object { ID=
28
, ProductID=
10
, Years=
1997
, more...}
, Object { ID=
29
, ProductID=
10
, Years=
1998
, more...}
]
more... meaning,that i have also the Quantity=5,6,8...  in the objects

and the result is that,the chart doesn't show(draw).only when the page is loading for the first time.

Also,can i change dynamically the title with the name of the Dropdownlist value?

Thanks in advance,
Daniel
0
Alexander Valchev
Telerik team
answered on 23 Jan 2013, 01:20 PM
Hi Daniel,

As soon as you change the data of the DataSource it will fire its change event which will cause all widgets that are bound to it to refresh. In other words, there is no need to call refresh or redraw methods - when data changes the Chart will refresh automatically.

Your code looks OK - the data is replaced correctly with the data method: chart.dataSource.data(e);
Could you send me a small runnable project with mock data that isolates the problem? In this way I would be able to examine what exactly is going wrong and provide you with a concrete recommendations. Please provide such project and I will check it right away. Thank you in advance for your cooperation.

Regarding your second question, "can i change dynamically the title with the name of the Dropdownlist value?".
The functionality is not supported out of the box, however there is a workaround that you may use. Please check this forum thread. Note that changing the Title does not cause change in the dataSource, which is why it is required to refresh the chat manually.

Regards,
Alexander Valchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Daniel
Top achievements
Rank 1
answered on 24 Jan 2013, 02:16 PM
Hello Alexander,
i managed to extract the code into a small project,the connection string should be changed to the local Northwind DB,it's a code first principle,so it has to exist the database.Also i used nuget package manager to download entity framework(search by "entity framework" nuget found ver. 5) and code first(search by "code first" found CTP 5).Because of the limit of atachments to 2MB,my project was around 4MB,so i removed the bin directory and the package directory.I hope you will manage to work or at least to see what is wrong in the project.
My result is: still doesn't draw the chart.the chart is made in javascript,only the dropdown and its values are in razor/mvc3 managed.

I hope you will see my mistake.

thanks in advance.
0
Alexander Valchev
Telerik team
answered on 27 Jan 2013, 10:10 PM
Hello Daniel,

Thank you for the sample project, I was able to run it on my side.

The problem is caused by the fact that "createChart" function is executed again right after the DataSource's data is replaced. Here is the relevant code (marked in red):
$.get("/Chart/GetSalesPerQuantityYear", { productID: $("#categor").val() }, function (e) {
    var chart = $("#chart").data("kendoChart");
    chart.dataSource.data(e); // data is replaced
    //...
    createChart(e); //chart is re-initialized with empty data
});

I am a bit confused because this line does not persists in the code snippets that you provided in your previous reply from Jan 21. Anyway, it re-initializes the chart with an empty DataSource which for the end user looks like the chart is not refreshed.

Once again, changing the DataSource's data will force the chart to refresh - there is no need to re-initialize it, nor to refresh/redraw it. This approach should work both when Chart is created via JavaScript and MVC Razor syntax.

Please apply the following modifications in the success event handler:
$.get(
    "/Chart/GetSalesPerQuantityYear",
    { productID: $("#categor").val() },
    function (e) {
        var chart = $("#chart").data("kendoChart");
        //change the data and refresh the chart
        chart.dataSource.data(e);
    }
);

I hope this will help. For your convenience I modified and attached back your project.

Kind regards,
Alexander Valchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Daniel
Top achievements
Rank 1
answered on 28 Jan 2013, 08:46 AM
i didn't provide that line of code,because initially it wasn't and still doesn't worked,in a way that it doesn't show anything at all not even the graph grid,so i put that line and the the grid was drawn,but no graph.
Now i removed that createGraph() from the change() function but, i still do not see anything,only the grid but no graph with bars(with break line,i see the bars but in the end disapear. and remains only the grid of the graph,but no graph(bars).

(also the example you sent me,need .net 4.5 and i saw that it needs too much space around 1.4GB,which i do not have on my C drive,so i cannot run your example because of the incompatibility with this error:
Method not found: 'Void System.Data.Objects.ObjectContextOptions.set_UseConsistentNullReferenceBehavior(Boolean)'
so the only solution is to change the code after your project code but.i do not understand why in your code is a function onBind(e) defined inside change()?!
the rest of the view is the same.

P.S:i had an error(error_1.jpg),but is because i deleted by mistake the <div id="chart" /> the only valid error is in error_2.jpg
0
Alexander Valchev
Telerik team
answered on 30 Jan 2013, 08:58 AM
Hello Daniel,

I did not updated the .NET version intentionally, I assume that Visual Studio 2012 did this automatically.

I ran your project on Visual Studio 2010. If you remove the Chart reinitialization the data refreshes as expected. Please check the screen cast: http://screencast.com/t/S0G8dgYFtn

As you can see:
  1. Initially Chart is initialized with empty dataSource (expected).
  2. When you select "Chai" as a product and createChart(e); persists in the code, the Chart does not refresh (as you described).
  3. If you commend that line and chart refreshes with the correct data.
  4. If you select product which do not have a data ("Alice Mutton") there will be no bars (expected).
  5. If you select another product which have data ("Chai", "Chang", "Aniseed Syrup") the chart refreshes and displays it correctly.

For you convenience I am attaching the updated project (VS 2010). Let me know if I missed something.

Kind regards,
Alexander Valchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Daniel
Top achievements
Rank 1
answered on 30 Jan 2013, 01:15 PM
very strange...i closed the firebug,and now finally it remains the chart,and its functionality is like  you describe it,first empty and after i select a product,now it remains the chart bars on the screen.

thanks again for all the suport.
Regards,
Daniel
Tags
Charts
Asked by
Daniel
Top achievements
Rank 1
Answers by
Alexander Valchev
Telerik team
Daniel
Top achievements
Rank 1
Share this question
or