Microsoft Charting, MVC 3 and Razor

后端 未结 3 910
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 11:01

Related to This topic I wonder if anyone has made the Microsoft Charting library working with Asp MVC 3 and Razor.

I know about the new chart helper introduced, but sinc

3条回答
  •  执念已碎
    2021-01-30 11:22

    I spent a few days looking for a solution that creates interactive charts in MVC, but all the examples I've seen were way more complicated than they have to be.

    The answer from Sarath is almost perfect, but it saves the image twice which is not very efficient. With the function Html.RenderAction() we can get everything done in one pass and make it as efficient as it can be.

    Here's the solution I came up with:

    http://blog.smirne.com/2012/09/creating-interactive-charts-with-aspnet.html

    I haven't seen any solution that can do everything in one pass. The best part of this is that it doesn't need any modifications to the web.config file. It also doesn't try to use an ASP.net control in MVC. It's pure MVC technology.

    UPDATE

    Here's code as requested:

    CONTROLLER:

    public ActionResult Chart()
    {
        var chart = buildChart();
        StringBuilder result = new StringBuilder();
        result.Append(getChartImage(chart));
        result.Append(chart.GetHtmlImageMap("ImageMap"));
        return Content(result.ToString());
    }
    

    Utility Functions:

    private Chart buildChart()
    {
        // Build Chart
        var chart = new Chart();
    
        // Create chart here
        chart.Titles.Add(CreateTitle());
        chart.Legends.Add(CreateLegend());
        chart.ChartAreas.Add(CreateChartArea());
        chart.Series.Add(CreateSeries());
    
        return chart;
    }
    
    private string getChartImage(Chart chart)
    {
        using (var stream = new MemoryStream())
        {
           string img = "";
           chart.SaveImage(stream, ChartImageFormat.Png);
           string encoded = Convert.ToBase64String(stream.ToArray());
           return String.Format(img, encoded);
        }
    }
    

    VIEW:

    @{ Html.RenderAction("Chart"); }
    

提交回复
热议问题