MVC3, Razor and MS Chart Controls in .NET 4

 

During this weekend I was elaborating with Microsoft Charting Tool and want with this blog post share the knowledge that I gained.

Demo

I started with an empty ASP.NET MVC 3 Web Application with the View engine Razor and I selected an Empty template. I added a reference to the assembly System.Web.DataVisualization.

Thereafter I created ViewModel called BarGraphViewModel.

 

using System.Web.UI.DataVisualization.Charting;

namespace Charters.Models
{
    public class BarGraphViewModel
    {
        public Chart BarChart
        {
            get { return BuildBarChart(); }
        }
        private Chart BuildBarChart()
        {
            var data = new BarData
            {
                xValues = new int[] { 1, 2, 3, 4 },
                yValues = new double[] { 0.3, 0.3, 0.1, 0.7 }
            };
            return BindChartData(data);
        }
        private Chart BindChartData(BarData data)
        {
            Chart chart = new Chart();
            chart.Width = 150;
            chart.Height = 150;

            chart.ChartAreas.Add(new ChartArea());
            chart.Series.Add(new Series());

            chart.Series[0].ChartType = SeriesChartType.Column;
            chart.Series[0].BackGradientStyle = GradientStyle.HorizontalCenter;
            chart.Series[0].BackSecondaryColor = System.Drawing.Color.Black;

            for (int i = 0; i < data.xValues.Length; i++)
            {
                int x = data.xValues[i];
                double y = data.yValues[i];
                int ptIdx = chart.Series[0].Points.AddXY(x, y);
                DataPoint pt = chart.Series[0].Points[ptIdx];
            }

            return chart;

        }
    }

    internal class BarData
    {
        public int[] xValues;
        public double[] yValues;
    }

}

 

After I created the viewmodel I created the Controller that I called BarGraphController.

using System.IO;
using System.Web.Mvc;
using Charters.Models;
using System.Web.UI.DataVisualization.Charting;

namespace Charters.Controllers
{
    public class BarGraphController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult DrawBarChart()
        {
            var viewModel = new BarGraphViewModel();
            Chart charter = viewModel.BarChart;
            MemoryStream ms = new MemoryStream();
            charter.SaveImage(ms, ChartImageFormat.Png);
            ms.Position = 0;
            return File(ms.GetBuffer(), "image/png");
        }
    }
}

Now it is time to create the view. I selected the Razor view and no strongly-typed view. In the view I added following line of code.

<a href="@Url.Action("DrawBarChart","BarGraph")"/>Graph

Compile and Run your web application. Don’t forget to enter correct path to the controller. My path are

http://localhost:54217/BarGraph/

Leave a Reply