HighCharts圖表控制項在ASP.NET WebForm中的使用

來源:互聯網
上載者:User

  Highcharts 是一個用純JavaScript編寫的一個圖表庫, 能夠很簡單便捷的在web網站或是web應用程式添加有互動性的圖表,並且免費提供給個人學習、個人網站和非商業用途使用。目前HighCharts支援的圖表類型有曲線圖、地區圖、柱狀圖、餅狀圖、散狀點圖和綜合圖表。

  HighCharts使用原理如所示:

 

  普通開發模式是在前端應用Jquery和HighChartsJS庫檔案,然後在<head>頭中寫Js指令碼,例如繪製餅圖Jquery指令碼如下:

 

繪製餅圖Jquery指令碼

$(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]                ]            }]        });    });

 

其中data屬性為圖表綁定資料來源。但這種方式也存在明顯問題:

  • 前端代碼量過大
  • 綁定動態資料比較困難,可取的方法是使用$.AJAX非同步方法呼叫解析WebServices或者一般處理常式ashx,然後對返回結果進行JSON序列化處理,比較麻煩容易出錯。
  • HighCharts的Js調用代碼無法實現代碼重用。

  解決方案是使用第三方HighCharts組件DoNet.HighCharts, 該組件是一個伺服器端產生HighCharts Js指令碼的開源組件,然後通過輸出資料流的方式插入到頁面Body塊的DIV中,原理如所示:

 

DoNet.HighCharts開發環境為(二選一)

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

  DoNet.HighCharts開源項目是以ASP.NET MVC3 Project的形式分發的,開發人員可以參考控制器檔案夾Controlls中的DemoController中每種圖表的後台代碼(和前台HighCharts JS代碼基本一致)

 

 

  MVC原理在這裡做簡單表述,便於程式員閱讀該代碼。

  • M:Module 模型層
  • V:View 視圖層
  • C:Controll 控制層

  當用戶端發送一個Action動作時,根據動作名找到Controll控制器中相應的方法名。例如http://localhost/Charts/Demo/BasicLine,MVC架構根據全域路由配置自動對應到BasicLine控制器方法,控制器方法返回一個Result並導航到Views檔案夾下的同名視圖BasicLine.cshtml(cshtml可以理解為WebForm的aspx)然後載入視圖。 

  Asp.net mvc和Asp.net Web Form方式不同,所以以上MVC實現方式需要修改才能在WebForm中使用。以下以“各種類產品均價統計功能”直條圖(涉及到NorthWind資料庫的Products和Categories表)為例說明WebForm中如何使用DoNet.HighCharts。

1:   建立查詢檢視View_CategoryAvgPrice

 

2:   建立強式名稱資料集NorthWind.xsd

 

  資料集分為強式名稱資料集和弱名稱資料集(DataSet)兩種,具體原理就不展開描述了。拖放View_CategoryAvgPrice和Categories表到資料集中。

3:   直條圖控制器方法(ColumnWithDrilldown)在aspx頁面中的主要代碼實現

 

直條圖控制器方法(ColumnWithDrilldown)在aspx頁面中的主要代碼實現

//匯入DoNet.HighCharts包using DotNet.Highcharts;using DotNet.Highcharts.Options;using DotNet.Highcharts.Enums;using DotNet.Highcharts.Helpers;using System.Drawing;using  NorthWindTableAdapters;/// <summary>/// 種類商品價格統計類/// </summary>public class CategoryPrice{    public Decimal Price { set; get; }    public string CategoryName { set; get; }}public partial class ColumnWithDrilldown : System.Web.UI.Page{    #region 建立強式名稱資料集表對象和資料配接器對象private NorthWind.View_CategoryAvgPriceDataTable avgPriceDt;avgPriceDt= new NorthWind.View_CategoryAvgPriceDataTable();    private NorthWind.CategoriesDataTable categoryDt = new NorthWind.CategoriesDataTable();    private View_CategoryAvgPriceTableAdapter avgPriceAdapter = new View_CategoryAvgPriceTableAdapter();    private CategoriesTableAdapter categoryAdapter = new CategoriesTableAdapter();    #endregion    private List<CategoryPrice> avgPriceList=null;//綁定資料來源集合    protected void Page_Load(object sender, EventArgs e)    {        LoadColumnWithDrilldown();    }    public void LoadColumnWithDrilldown()    {        avgPriceAdapter.Fill(avgPriceDt);        categoryAdapter.Fill(categoryDt);        //按產品種類分組顯示Linq運算式         avgPriceList =             (                  from p in avgPriceDt                  group p by p.CategoryID into g//根據種類編號分組                  select new CategoryPrice                  {                      //種類名稱                      CategoryName=categoryDt.First(c=>c.CategoryID==g.Key).CategoryName,                      //種類商品均價                      Price = g.Average(c => c.UnitPrice)                  }              ).ToList();        //顯示直條圖的種類名稱數組        string[] categories = new string[avgPriceList.Count()];        int index = 0;        foreach (var item in avgPriceList)        {            categories[index++] = item.CategoryName;        }        Data data = LoadDate();//直條圖動態繫結資料源       //省略HighCharts指令碼代碼,同mvc代碼        div1.InnerHtml = chart.ToHtmlString();//轉換為HighCharts的用戶端指令碼插入到div1中}   //根據匯總的種類商品建立直條圖節點對象的方法    private  Data LoadDate()    {            Data data = null;            int index =-1;           //建立直條圖顯示的節點對象            DotNet.Highcharts.Options.Point []pointList=new DotNet.Highcharts.Options.Point[avgPriceList.Count];            foreach (var item in avgPriceList)            {                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;           }}

 

顯示效果如所示:

 開源項目DoNet.HighCharts網址:http://dotnethighcharts.codeplex.com/

 HighCharts Jquery網址:http://www.highcharts.com/demo/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.