Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KendoUI charts with Asp.net MVC

I am looking for tutorials and code examples on how to display a KendoUI chart on a web page with data fetched from a database. More precisely an ASP.Net MVC webpage; like what needs to be done on the server side to be able to show data calculated on controller method displayed on the KendoUI chart.

Questions specifically are:

  1. Does KendoUI work only with services or can I even return ViewModel object in an ActionResult method as return View(vmObj); ?
  2. Is there any example of code on the server side that returns to a KendoUI chart?
  3. Does KendoUI only work in MVC or can I use it in Asp.Net WebForms also

The KendoUI docs that I have seen so far only show client side code and are not tailored towards AspNet MVC developers.

Thanks for your time..

like image 829
user20358 Avatar asked Aug 09 '12 14:08

user20358


1 Answers

Kendo used to have some ASP.NET MVC demos which you could download and run in Visual Studio to see how to bind to remote data and such, but they were removed for some reason. Here is a simple example I made based on those demos:

Controller actions (in "ChartsController.cs", for example):

public ActionResult Index()
{
    return View();
}
public ActionResult GetChartData()
{
    IEnumerable<ChartModel> chartData = SomeRepository.GetData();
    return Json(chartData);
}

ChartModel:

public class ChartModel
{
    public ChartModel(string year, int val2, int val3)
    {
        Year = year;
        Val2 = val2;
        Val3 = val3;
    }
    
    public string Year { get; set; }
    public int Val2 { get; set; }
    public int Val3 { get; set; }
}

View ("Charts/Index.cshtml", layout not included):

<div class="chart-wrapper">
@(Html.Kendo().Chart<ChartExample.Models.ChartModel>()
    .Name("chart")
    .Title("Example Column Chart")
    .Legend(legend => legend
        .Position(ChartLegendPosition.Top)
    )
    .DataSource(ds => ds.Read(read => read.Action("GetChartData", "Charts")))
    .Series(series => {
        series.Column(model => model.Val2).Name("Val2");
        series.Column(model => model.Val3).Name("Val3");
    })
    .CategoryAxis(axis => axis
        .Categories(model => model.Year)
        .Labels(labels => labels.Rotation(-90))
    )
    .ValueAxis(axis => axis.Numeric()
        .Labels(labels => labels.Format("{0:N0}"))
        .MajorUnit(10000)
    )
) 
</div>

This example uses separate controller actions for getting the view and getting the chart's data, but you could also combine them and have return View(chartData); and just have in your view:

@model IEnumerable<ChartExample.Models.ChartModel>
<div>
    @(Html.Kendo().Chart(Model)
        // just don't include the ".DataSource" line
        // ...
    )
</div>

Unfortunately, I can't tell you if it can be done with Webforms as I've never used that before. Hope this helps!

like image 165
Alejo Avatar answered Oct 20 '22 04:10

Alejo