Saturday 18 May 2019

MVC - Charting - Create simple chart from database using Entity Framework - Step By Step

Watch this example on YouTube:



1. Table

USE [Company]
GO

/****** Object:  Table [dbo].[ChartTest]    Script Date: 2019-05-18 3:31:57 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[ChartTest](
    [ProductName] [varchar](50) NULL,
    [Month] [varchar](50) NULL,
    [Amount] [int] NULL
) ON [PRIMARY]

GO

2. Stored Procedure

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
CREATE PROCEDURE GetProducts

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT * FROM ChartTest
END
GO

3. Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication3.Models;
using System.Web.UI.DataVisualization.Charting;
using System.IO;
using System.Text;
using System.Drawing;

namespace WebApplication3.Controllers
{
    public class HomeController : Controller
    {
        CompanyEntities db = new CompanyEntities();

        public ActionResult ChartFromEF()
        {
            var data = db.GetProducts().ToList();
            var chart = new Chart();
            var area = new ChartArea();
            chart.ChartAreas.Add(area);
            var series = new Series();
            foreach(var item in data)
            {
                series.Points.AddXY(item.ProductName, item.Amount);
            }
            series.Label = "#PERCENT{P0}";
            series.Font = new Font("Arial", 8.0f, FontStyle.Bold);
            series.ChartType = SeriesChartType.Column;
            series["PieLabelStyle"] = "Outside";
            chart.Series.Add(series);
            var returnStream = new MemoryStream();
            chart.ImageType = ChartImageType.Png;
            chart.SaveImage(returnStream);
            returnStream.Position = 0;
            return new FileStreamResult(returnStream, "image/png");
        }

4. View

@{
    ViewBag.Title = "ChartFromEF";
}

<h2>ChartFromEF</h2>

<img src="@Url.Action("ChartFromEF")" />

No comments:

Post a Comment