Saturday 25 May 2019

MVC - Chart - Create Simple Chart and load data from DB - Entity Framework



Watch this example on YouTube


 

1. Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication7.Models;
using System.Collections;
using System.Web.Helpers;


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

        public ActionResult GetChartImage()
        {
            ArrayList xValue = new ArrayList();
            ArrayList yValue = new ArrayList();
            var results = db.GetProducts().ToList();
            results.ToList().ForEach(rs => xValue.Add(rs.Month));
            results.ToList().ForEach(rs => yValue.Add(rs.Amount));
            var key = new Chart(width: 300, height: 300)
                .AddTitle("Months")
                .AddSeries(chartType: "Pie",
                name: "Some Name",
                xValue: xValue,
                yValues: yValue);
            return File(key.ToWebImage().GetBytes(), "image/jpeg");
        }

        public ActionResult Index()
        {
            return View();
        }

2. View

@{
    ViewBag.Title = "Home Page";
}


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

No comments:

Post a Comment