Search code examples
asp.net-mvc-3razorhtml-helper

MVC3 Chart Helper with data as parameter


I'm dealing with the chart helper of mvc framework and I wonder if there is a way to add dynamic data into the chart. all the tutorials (e.g. http://www.asp.net/webmatrix/tutorials/7-displaying-data-in-a-chart) use hard coded data.

What if I want to pass the data, for example a list of stocks and display the data in the charts.

I'm including the chart with:

 <img src="@Url.Action("GenerateChart", new {data = stocks})" alt="stocks" />

The possible code of the action methode:

 public FileContentResult GenerateChartImage(IList<StockProgressionModel> data)
    {
        Chart chart = new Chart(800, 600);

        foreach (var stock in data {

            int[] xArray = Enumerable.Range(0, stock.Entries.Count).ToArray();
            var yArray = stock.Entries.Select(e => e.Value).ToArray();

            chart.AddSeries(ap.FieldOfActivityName, chartType: "FastLine",
                            xValue: xArray,
                            yValues: yArray);
            chart.SetXAxis("Month", 0);
            chart.SetYAxis("Value", 0);
        }

        return File(chart.GetBytes(), "image/png");
    }

This means that the link of the url is always the same and I cannot pass the data as parameter. Is there a better way to do this?


Solution

  • I found a solution:

    View:

    @{
        string key = Guid.NewGuid().ToString();
        @Html.Action("GenerateChart", new { @cacheKey = key, data = stocks })
        string url = Url.Action("ShowChart", new { @cacheKey = key });
        <img src="@url" alt="Chart" />
    }
    

    Controller:

    public void GenerateChartImage(IList<StockProgressionModel> data)
    {
        Chart chart = new Chart(800, 600);
    
        foreach (var stock in data {
    
            int[] xArray = Enumerable.Range(0, stock.Entries.Count).ToArray();
            var yArray = stock.Entries.Select(e => e.Value).ToArray();
    
            chart.AddSeries(ap.FieldOfActivityName, chartType: "FastLine",
                            xValue: xArray,
                            yValues: yArray);
            chart.SetXAxis("Month", 0);
            chart.SetYAxis("Value", 0);
        }
        chart.SaveToCache(cacheKey, 1);
    }
    
    public void ShowChart(string cacheKey)
    {
        Chart chart = Chart.GetFromCache(cacheKey);
        chart.Write("jpeg");
    }
    

    If someone had a better solution, i would be interested.