Telerik blogs

With the release of Q2 2011 we here at Telerik are proud to announce the Chart Extension for ASP.NET MVC. This component has been designed from the ground up with a high focus on performance and cross-browser compatibility and is based off of SVG and VML (for browsers that do not support SVG). Many of you are probably interested in how you can start working with the chart and this blog post should help guide you along the first couple of steps.

Server Binding

Out-of-the-box the chart component can very easily bind to any supplied model on the server. If the view is strongly typed this is made even easier as you can just pass the view’s Model object. The data in this model will be serialized to the client for you, very nice and easy. To get started lets go ahead and create some data. I have the following class called SalesData.cs, which I added to my Models folder:

using System.Collections.Generic;
 
namespace ChartApplication.Models
{
    public class SalesData
    {
        public string RepName { get; set; }
 
        public string DateString { get; set; }
 
        public decimal TotalSales { get; set; }
 
        public decimal RepSales { get; set; }
    }
 
    public static class SalesDataBuilder
    {
        public static List<SalesData> GetCollection()
        {
            return new List<SalesData>
            {
                new SalesData
                {
                    RepName = "Nancy Davolio",
                    DateString = "Aug 2010",
                    TotalSales = 15458,
                    RepSales = 2015
                },
 
                new SalesData
                {
                    RepName = "Nancy Davolio",
                    DateString = "Sept 2010",
                    TotalSales = 26598,
                    RepSales = 6003
                },
 
                new SalesData
                {
                    RepName = "Nancy Davolio",
                    DateString = "Oct 2010",
                    TotalSales = 27623,
                    RepSales = 6881
                },
 
                new SalesData
                {
                    RepName = "Nancy Davolio",
                    DateString = "Nov 2010",
                    TotalSales = 41167,
                    RepSales = 4060
                },
 
                new SalesData
                {
                    RepName = "Nancy Davolio",
                    DateString = "Jan 2011",
                    TotalSales = 49663,
                    RepSales = 10254
                },
 
                new SalesData
                {
                    RepName = "Nancy Davolio",
                    DateString = "Feb 2011",
                    TotalSales = 50896,
                    RepSales = 9546
                },
 
                new SalesData
                {
                    RepName = "Nancy Davolio",
                    DateString = "Mar 2011",
                    TotalSales = 34714,
                    RepSales = 7332
                },
            };
        }
    }
}

Side-note: this is the same data as used in our online demos, in-case you’re wondering why it looks so similar.

As we can see in the code above I just have a couple of simple properties: RepName, DateString, TotalSales, and Repsales. I also have another class inside that creates a new List of SalesData via the GetCollection method. This is all very simple data, but it gives you an idea of how data can be structured. Now, in terms of our controller it’s pretty easy to set everything up since we merely have to return the result of the GetCollection method:

public ActionResult Server()
{
    return View(SalesDataBuilder.GetCollection());
}

How easy was that? When we move over to the actual view itself we have some more configurations to do. Before we get started with our code let’s add an @model declaration simply saying that our Model is an IEnumerable of type SalesData.

@model IEnumerable<SalesData>

With that out of the way, the simplest way for us to get started is to do the following:

@{Html.Telerik().Chart(Model)
      .Name("TelerikChart")
      .Series(series =>
      {
          series.Bar(o => o.RepSales);
      })
      .CategoryAxis(axis => axis.Categories(c => c.DateString))
      .Render();
}

This does a couple of things. First of all, we’re creating a Chart, giving it a name and then rendering it – that’s all standard for working with our ASP.NET MVC Extensions. Of course you can use ( … ) instead of { … } and not include the .Render(); at the end. We have passed in our Model, which is just of the SalesData type. What makes a Chart special is of course the ability to have multiple series and taking a look at how we define the (for now) only series in our chart we see that a simple lambda expression is used and thanks to us passing the Model using “o => o.” will grant is intellisense for the various properties available.

Some questions might be popping up here regarding the CategoryAxis property. All that I’m doing is defining that I want the DateString property to be associated with the X-axis of my chart. If I left this out the chart would still render, all items on the x-axis would just be tied with an “undefined” string, since in this case I wouldn’t have defined any labels for them.

When we navigate to the view which we defined all of this on we now see that we have a chart – great success! Let’s take a look at the HTML we’ve generated:

Chart SVG Output

So with the few lines of code we had in our MVC view we have created an SVG chart. I’m not going to go much deeper into what all of this SVG code means, but it’s good to know what a rendered component might look like.

Ajax Binding

So that was server binding, what about using Ajax? Well, luckily it’s not much more complicated at all. Let’s work with the same data as we had above. In terms of the controller we have to define an ActionResult that returns Json which can look a little something like this:

public ActionResult Ajax()
{
    return View();
}
 
public ActionResult _SalesData()
{
    return Json(SalesDataBuilder.GetCollection());
}

Looks essentially the same as with the above server binding approach, aside from the return Json( … ) part. We’re still returning the same collection however, so the same data is there. How do we take use of this in our view? Well, we have to define Ajax binding using the following line:

.DataBinding(databinding => databinding.Ajax().Select("_SalesData", "Chart"))

Aside from that it’s very similar. So, what does my View look like overall?

@{Html.Telerik().Chart<SalesData>()
      .Name("TelerikChart")
      .Series(series =>
      {
          series.Bar(s => s.RepSales);
      })
      .CategoryAxis(axis => axis.Categories(s => s.DateString))
      .DataBinding(databinding => databinding.Ajax().Select("_SalesData", "Chart"))
      .Render();
}

Pretty much exactly the same as my server binding scenario above. The only difference, as mention before, is the DataBinding method that we use.

One more thing that I wanted to mention about Ajax binding is that you can very easily pass a parameter to the function by doing the following in the DataBinding declaration:

.DataBinding(databinding => databinding.Ajax().Select("_SalesData", "Chart", new { year = ViewBag.Year } ))

And then this in the controller:

public ActionResult _SalesData(int? year)
{
    return Json(SalesDataBuilder.GetCollection(year));
}

More Configuration Options

So now you know how to bind your data either via server or Ajax binding. These charts have been pretty simple though, what other options do you have available? The following view, which takes use of the same server binding as my first example, gives some further insights:

@{Html.Telerik().Chart(Model)
      .Name("TelerikChartTwo")
      .Series(series =>
      {
          series.Bar(o => o.RepSales).Labels(true).Name("Representative Sales").Gap(1);
          series.Bar(o => o.TotalSales).Name("Total Sales");
      })
      .CategoryAxis(axis => axis.Categories(c => c.DateString))
      .Title("Awesome Chart Title")
      .Legend(legend => legend.Visible(true).Position(ChartLegendPosition.Custom))
      .Render();
}

Taking a look over all of this from a top-to-bottom approach we can see that the first difference is in my RepSales series. I have used the labels property (normally set to false as default) to true, which shows a label containing the value of each series item. I have also given a name to my series (using the .Name method) which can be used to, for example, define what the series will appear as in my legend (more on the legend in a second). I also have used the Gap property which represents the white space between series items, and it is set as 1.5 by default (experiment a bit with this one in your own chart by setting it to 5 to see some real difference). I also added a new series just to show some contrast :)

The chart extension also has the ability for you to define a title using the .Title method, which just takes a string as a parameter. Finally, I specifically defined the legend to be visible. Although it is visible by default you can set this to be hidden and also define what position it should be rendered in, which can be Top, Bottom, Left, Right or even a Custom position. The later uses an OffsetX and OffsetY to handle the layout of the legend item.

Conclusion

So there we go; a first look at the Telerik Chart Extension for ASP.NET MVC. You should have a good idea of how to work with this component both in server and Ajax binding modes. For more examples and insight into this new component I highly recommend taking a look at our online demos as well as our online documentation. With this first release we support the Bar, Column and Line chart types, but this list will quickly expand with each upcoming release. Below you will find a link to the sample project which contains all of the code above. Simply add /chart/server or /chart/ajax to the end of the URL when you land on the initial page. I have not included the Telerik.Web.MVC assembly for the sake of having a small download, but you can just include your own, as long as it’s Q2 2011 or later ;)

ChartApplication


Carl Bergenhem
About the Author

Carl Bergenhem

Carl Bergenhem was the Product Manager for Kendo UI.

Related Posts

Comments

Comments are disabled in preview mode.