Use of the HighCharts chart control in ASP. NET WebForm

Source: Internet
Author: User

Highcharts is a graph library written in pure JavaScript. It is easy and convenient to add interactive charts on websites or web applications, it is also free for personal learning, personal websites, and non-commercial use. Currently, HighCharts supports the following chart types: curve chart, region chart, column chart, pie chart, scatter chart, and comprehensive chart.

Shows how HighCharts works:

 

The common development mode is to apply the Jquery and HighChartsJS library files at the front end, and then write the Js script in the

 

Jquery script for creating a pie chart

$(function () {        $('#container').highcharts({            chart: {                plotBackgroundColor: null,                plotBorderWidth: null,                plotShadow: false            },            title: {                text: 'Browser market shares at a specific website, 2010'            },            tooltip: {                pointFormat: '{series.name}: <b>{point.percentage}%</b>',                percentageDecimals: 1            },            plotOptions: {                pie: {                    allowPointSelect: true,                    cursor: 'pointer',                    dataLabels: {                        enabled: true,                        color: '#000000',                        connectorColor: '#000000',                        formatter: function() {                            return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';                        }                    }                }            },            series: [{                type: 'pie',                name: 'Browser share',                data: [                    ['Firefox',   45.0],                    ['IE',       26.8],                    {                        name: 'Chrome',                        y: 12.8,                        sliced: true,                        selected: true                    },                    ['Safari',    8.5],                    ['Opera',     6.2],                    ['Others',   0.7]                ]            }]        });    });

 

The data attribute is used to bind data sources to charts. However, this method also has obvious problems:

  • Excessive front-end code
  • It is difficult to bind dynamic data. The recommended method is to use the $. AJAX Asynchronous Method to parse WebServices or the general processing program ashx, and then serialize the returned results in JSON format, which is troublesome and error-prone.
  • The Js calling code of HighCharts cannot be reused.

The solution is to use the third-party HighCharts component DoNet. highCharts: an open-source component that generates HighCharts Js scripts on the server side. It is then inserted into the DIV of the page Body block using the output stream. The principles are shown in:

 

DoNet. HighCharts Development Environment (either)

  • VS2008 + ASP. NET MVC3 +. NET 3.5
  • VS2010 +. NET 4.0

The DoNet. HighCharts open-source Project is distributed in the form of an ASP. NET MVC3 Project. developers can refer to the background code of each chart in the Controller folder Controlls (basically consistent with the foreground HighCharts JS Code)

 

 

The MVC principle is briefly described here to facilitate programmers to read the code.

  • M: Module model layer
  • V: View Layer
  • C: Controll control layer

When the client sends an Action, find the corresponding method name in the Controll controller based on the Action name. For example, http: // localhost/Charts/Demo/BasicLine, the MVC Framework automatically maps to the BasicLine Controller Method Based on the global routing configuration, the Controller method returns a Result and navigate to the BasicLine view with the same name under the Views folder. cshtml (cshtml can be understood as the aspx of WebForm) and then load the view.

Asp.net mvc and Asp.net Web Form are different. Therefore, the above MVC implementation method must be modified before it can be used in WebForm. The following uses the "average price statistics for various Products" column chart (involving the Products and Categories tables of the NorthWind database) as an example to describe how to use DoNet. HighCharts in WebForm.

1: Create a query view view_categoryavuplice

 

2: create a strong name dataset NorthWind. xsd

 

Datasets are classified into strong-name datasets and weak-name datasets. The detailed principles are not described. Drag the view_categoryavuplice and Categories tables to the dataset.

3: Main Code Implementation of the bar chart Controller method (ColumnWithDrilldown) on the aspx page

 

Main Code Implementation of the bar chart Controller method (ColumnWithDrilldown) on the aspx page

// Import DoNet. highCharts package using DotNet. highcharts; using DotNet. highcharts. options; using DotNet. highcharts. enums; using DotNet. highcharts. helpers; using System. drawing; using NorthWindTableAdapters; // <summary> // product Price statistics /// </summary> public class CategoryPrice {public Decimal Price {set; get ;} public string CategoryName {set; get;} public partial class ColumnWithDrilldown: System. web. UI. page {# region create a strong name dataset table object and data adapter object private NorthWind. view_categoryavuplicedatatable avuplicedt; avuplicedt = new NorthWind. view_categoryavuplicedatatable (); private NorthWind. categoriesDataTable categoryDt = new NorthWind. categoriesDataTable (); private view_categoryavuplicetableadapter avupliceadapter = new category (); private CategoriesTableAdapter categoryAdapter = new CategoriesTableAdapter (); # endregion private List <CategoryPrice> avuplicelist = null; // bind the data source set protected void Page_Load (object sender, EventArgs e) {LoadColumnWithDrilldown ();} public void LoadColumnWithDrilldown () {avupliceadapter. fill (avuplicedt); categoryAdapter. fill (categoryDt); // display the Linq expression avuplicelist = (from p in avuplicedt group p by p. categoryID into g // select new CategoryPrice by category ID {// category name CategoryName = categoryDt. first (c => c. categoryID = g. key ). categoryName, // average Price of a product type = g. average (c => c. unitPrice )}). toList (); // display the type name array of the column category string [] categories = new string [avuplicelist. count ()]; int index = 0; foreach (var item in avuplicelist) {categories [index ++] = item. categoryName;} Data data = LoadDate (); // the Data source dynamically bound to the column chart // The HighCharts script code is omitted, which is the same as the mvc code div1.InnerHtml = chart. toHtmlString (); // The client script converted to HighCharts is inserted into div1} // The method of creating a column worker Node object based on the summary type item private Data LoadDate () {Data data = null; int index =-1; // create the Node object DotNet. highcharts. options. point [] pointList = new DotNet. highcharts. options. point [avuplicelist. count]; foreach (var item in avuplicelist) {pointList [++ index] = new DotNet. highcharts. options. point {Y = (Number) (item. price * 100)/100.0, Color = Color. fromName (string. format ("colors [{0}]", index) };} data = new Data (pointList); return data ;}}

 

Shows the display effect:

Open Source Project DoNet. HighCharts Web site: http://dotnethighcharts.codeplex.com/

HighCharts Jquery Web site: http://www.highcharts.com/demo/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.