Highcharts in MVC

Creating Highcharts in MVC


Steps for Create Highchart
1.        Download highcharts  from Here Or install via Nuget Package manager
2.       Copy & past HighCharts folder in scripts folder
3.       Add js files to your layout page
 

Your Layout page should Look Like this
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    <script src="~/Scripts/Highcharts/highcharts.js"></script>
    <script src="~/Scripts/Highcharts/themes/grid-light.js"></script>
</head>
<body>

    @Html.Action("TopNav","Navigation")     @*Navbar rendering*@

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My Application</p>
        </footer>
    </div>
    @RenderSection("scripts", required: false)
</body>
</html>
1.       Add class to model folder (GraphModal)
GrphModal class should look like this.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ExportToExcel.Models
{
    public class GraphModal
    {
        public string Course { get; set; }
        public int Students { get; set; }
    }
}
2.       Run the following script in your target database for creating tables and adding records

CREATE TABLE [dbo].[Course](
      [CourseID] [int] NOT NULL,
      [CourseName] [varchar](200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
 CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED
(
      [CourseID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Student](
      [StudentID] [int] NOT NULL,
      [Name] [varchar](200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [RegNo] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [Address] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [CourseID] [int] NULL,
 CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED
(
      [StudentID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[Student]  WITH CHECK ADD  CONSTRAINT [FK_Student_Course] FOREIGN KEY([CourseID])
REFERENCES [dbo].[Course] ([CourseID])
GO
INSERT INTO dbo.Course VALUES (1,'C#')
INSERT INTO dbo.Course VALUES (2,'C++')
INSERT INTO dbo.Course VALUES (3,'Asp.net')


INSERT INTO [Student] VALUES(1,'abc','reg 1','Address 1',1)
INSERT INTO [Student] VALUES(2,'xyz','reg 2','Address 2',1)
INSERT INTO [Student] VALUES(3,'bnm','reg 3','Address 3',1)
INSERT INTO [Student] VALUES(4,'abc','reg 4','Address 1',1)
INSERT INTO [Student] VALUES(5,'xyz','reg 5','Address 2',1)
INSERT INTO [Student] VALUES(6,'bnm','reg 6','Address 3',1)

INSERT INTO [Student] VALUES(7,'st 1','reg 1','Address 1',2)
INSERT INTO [Student] VALUES(8,'st2','reg 2','Address 2',2)
INSERT INTO [Student] VALUES(9,'st3','reg 3','Address 3',2)
INSERT INTO [Student] VALUES(10,'st4','reg 4','Address 1',2)
INSERT INTO [Student] VALUES(11,'st5','reg 5','Address 2',2)
INSERT INTO [Student] VALUES(12,'st6','reg 6','Address 3',2)
INSERT INTO [Student] VALUES(13,'st7','reg 5','Address 2',2)
INSERT INTO [Student] VALUES(14,'st8','reg 6','Address 3',2)

INSERT INTO [Student] VALUES(15,'st 1','reg 1','Address 1',3)
INSERT INTO [Student] VALUES(16,'st2','reg 3','Address 3',3)
INSERT INTO [Student] VALUES(17,'st3','reg 3','Address 3',3)
INSERT INTO [Student] VALUES(18,'st4','reg 4','Address 1',3)
INSERT INTO [Student] VALUES(19,'st5','reg 5','Address 3',3)
INSERT INTO [Student] VALUES(20,'st6','reg 6','Address 3',3)
INSERT INTO [Student] VALUES(21,'st7','reg 5','Address 3',3)
INSERT INTO [Student] VALUES(22,'st8','reg 6','Address 3',3)
INSERT INTO [Student] VALUES(23,'st8','reg 6','Address 3',3)
INSERT INTO [Student] VALUES(24,'st8','reg 6','Address 3',3)

3.       Add controller(ChartsController)  to your project. Should look like this


 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Data;
using ExportToExcel.Models;
namespace ExportToExcel.Controllers
{
    public class ChartsController : Controller
    {
        // GET: Charts
        public ActionResult ShowGraph()
        {
            return View();
        }
        [HttpPost]
        public JsonResult GenerateGraph()
        {
            SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=Accounting; Integrated Security=SSPI;");
            SqlDataAdapter da = new SqlDataAdapter(@"SELECT     Course.CourseName AS Course, COUNT(Student.StudentID) AS Students
FROM         Student INNER JOIN
                      Course ON Student.CourseID = Course.CourseID
GROUP BY Course.CourseName", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            List<GraphModal> lst = new List<GraphModal>();
            foreach(DataRow row in dt.Rows)
            {
                lst.Add(new GraphModal() { Course=row["Course"].ToString(), Students=int.Parse(row["Students"].ToString()) });
            }
            return Json(lst, JsonRequestBehavior.AllowGet);
        }
    }
}

1.        Add view to ShowGraph() action Method. Should look like this.


@{
    ViewBag.Title = "ShowGraph";
    Layout = "~/Views/Shared/_MyLayout.cshtml";
}


<script language="javascript">
    var course = [];
    var students = [];

    
    $(function () {
        $.fn.extend({
            StudentsByCourse: function () {
                $.ajax({
                    type: "POST",
                    url: "GenerateGraph",
                    data: '{}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        course = []; students = [];
                        $.each(data, function (i, x) {
                            course.push(x.Course);
                            students.push(x.Students);
                            
                        });
                    },
                    failure: function (response) {
                        alert(response.d);
                    }
                });
                $('#studentbycourse').highcharts({
                    chart: {
                        type: 'column', width: 830
                    },
                    title: {
                        text: 'Students By Course'
                    },
                    xAxis: {
                        categories: course,
                        crosshair: true
                    },
                    yAxis: {
                        min: 0,
                        title: {
                            text: 'Students'
                        }
                    },
                    tooltip: {
                        headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                        pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                            '<td style="padding:0"><b>{point.y:.0f}</b></td></tr>',
                        footerFormat: '</table>',
                        shared: true,
                        useHTML: true
                    },
                    plotOptions: {
                        column: {
                            pointPadding: 0.2,
                            borderWidth: 0,
                            dataLabels: {
                                enabled: true,
                                rotation: 40,
                                softConnector: true,
                                y: -8
                            }
                        }

                    },
                    series: [{
                        showInLegend: false,
                        name: 'Students',
                        data: students

                    }]
                });
                $("text:contains('Highcharts.com')").css('display', 'none');
            }
        });
    });

        //$("text:contains('Highcharts.com')").css('display', 'none');
    $(function () {
        $.fn.StudentsByCourse();
    });

</script>
    <h2>Show Graph</h2>
   <div class="panel panel-primary">
     <div class="panel-heading">Students Graph</div>
     <div class="panel-body">
        <div id="studentbycourse"></div>
     </div>
   </div>
 
  


Now run your project and navigate to charts/showgraph

1 Comments

  1. Hi Zafar

    Sorry bro but it shows highcharts is not a function error rest seems fine.
    Can you send me the js that you are using in the code.

    ReplyDelete

Post a Comment