導讀
如果想在一個頁面里實例化帶分類篩選的多個Echarts該怎么做呢?
曾探討了帶分類選擇的關系圖顯示為自定義圖片的需求實現,傳送門ECharts圖表插件(4.x版本)使用(一、關系圖force節點顯示為自定義圖像/圖片,帶分類選擇)
本篇將着重介紹如何根據后台返回的列表數據,實例化多個Echarts,對應所用技術點:Asp.Net MVC & Razor 視圖引擎
最終產品效果圖
產品需求幾經變化,由加載全部圖表到默認只展示一個圖表,再到節點展示改為圖像等;
加載全部圖表,多個ECharts
默認只展示一個圖表,有分類篩選功能
默認只展示一個圖表,節點展示改為圖像,有分類篩選功能
實現思路
帶有篩選功能展示不同Echarts圖表,而不是一個ECharts圖表里的篩選功能,此需求實現,采用一次性實例化多個ECharts,隱藏掉其余實例,而不是切換分類時請求數據,進行實例化。
后台返回數據在razor視圖模板里接收
@{ Layout = "~/Views/Shared/_xkLayout.cshtml"; List<xk_group> listGroup = ViewBag.Group; List<ScholarDto> list = ViewBag.List; List<IGrouping<long?, ScholarDto>> listGrouping = ViewBag.Grouping; }
html代碼,含c#語法
<div class="rc left" id="ResultData"> <!--學者--> <div class="scholar"> <div class="choose clearfix"> @if (listGrouping != null && listGrouping.Count > 0) { foreach (var item in listGrouping) { <a href="javascript:;" data-groupid="@item.Key" data-groupname="@item.FirstOrDefault().GroupName">@item.FirstOrDefault().GroupName</a> } } </div> @if (listGroup != null && listGroup.Count > 0) { foreach (var item in listGroup) { <div name="scholarRechart"> @*<h1>研究“@(item.GroupName)”的學者</h1>*@ <div id="relationChart_@item.GroupId" data-groupid="@item.GroupId" data-groupname="@item.GroupName" style="width: 600px; height: 400px;"> </div> </div> } } </div> </div>
js代碼 實例化多個ECharts
@if (listGrouping != null && listGrouping.Count > 0) { foreach (var item in listGrouping) { <text> @*var groupName = "@item.FirstOrDefault().GroupName";*@ $(function () { var nodes_@item.Key = [{ //category: 0, name: "@item.FirstOrDefault().GroupName", //color: "green", symbol: "circle",//"image://http://thumb12.jfcdns.com/2018-06/bce5b231ad7df722.png", symbolSize: 100, size: 100, label: "@item.FirstOrDefault().GroupName", x: null, y: null, draggable: true, //cursor:"pointer", label: { show: true, textStyle: { color: '#333', fontSize: 18, fontWeight: "bolder" }, position: 'inside',//標簽位置 //distance: 50//標簽距離圖形的距離 }, }]; var links_@(item.Key) = []; @*var legendData_@(item.Key) = [];*@ @{ var subList = item.ToList(); if (subList != null && subList.Count > 0) { foreach (var subItem in subList) { <text> nodes_@(item.Key).push({ //category: 1, name: "@subItem.RealName", //color:"green", symbol: 'image://@ProductConfigHelper.DomainXinKeUrl/imagesTemp/potrait/0@(random.Next(1,6)).png', symbolSize: 60, size: 60, x: null, y: null, //draggable: true, scholarUrl: "@subItem.Link" }); links_@(item.Key).push( { source: "@subItem.RealName", target: "@subItem.GroupName", weight: 6, name: "@subItem.RealName" }); </text> } <text> //// 基於准備好的dom,初始化echarts實例 var myChart_@(item.Key) = echarts.init(document.getElementById('relationChart_@item.Key')); option_@(item.Key) = { title: { text: '研究“@(item.FirstOrDefault().GroupName)”的學者', subtext: '', //x: 'middle', //y: 'top', //textStyle: { // align: "center", //} //top: "middle", //bottom: "150", left: "center" }, tooltip: { trigger: 'item', formatter: '{b}' }, toolbox: { show: true, feature: { //restore: { show: true }, magicType: { show: true, type: ['force', 'chord'] }, //saveAsImage: { show: true } } }, @*legend: { x: 'left', data: legendData_@(item.Key)//['作者', '家人', '朋友'] },//分類*@ //edgeLength: [500, 100], series: [ { type: 'graph', //name: "相關學者", cursor: "pointer", draggable: false, layout: 'force', //symbol: 'pin', ribbonType: false, //categories: seriesCategories, cursor:'pointer', itemStyle: { normal: { color: "#2ec7c9",//節點顏色 label: { show: true, textStyle: { color: '#333' }, position: 'bottom',//標簽位置 distance: 5//標簽距離圖形的距離 }, nodeStyle: { brushType: 'both', borderColor: 'rgba(255,215,0,0.4)', borderWidth: 1 }, linkStyle: { type: 'line' } }, emphasis: { label: { show: false // textStyle: null // 默認使用全局文本樣式,詳見TEXTSTYLE }, nodeStyle: { //r: 30 }, linkStyle: {} } }, //useWorker: false, minRadius: 15, maxRadius: 25, //gravity: 0.1, //scaling: 0.1, roam: 'scale',//設置成可縮放 nodes: nodes_@(item.Key), links: links_@(item.Key), force: { repulsion: 1000 } } ] }; // 使用剛指定的配置項和數據顯示圖表。 myChart_@(item.Key).setOption(option_@(item.Key)); //節點點擊事件 myChart_@(item.Key).on('click', function (param) { if (param.data.scholarUrl) { window.open(param.data.scholarUrl); } }); </text> } } }) </text> } }
在script標簽里,使用razor視圖模板語法,在C#代碼里輸出js代碼,使用<text></text>標簽即可。
后台獲取Echarts所需相關數據的方法及相關model
#region 獲取相關學者列表 /// <summary> /// 獲取相關學者列表 /// </summary> /// <param name="id"></param> /// <returns></returns> public JsonpResult GetScholarRelation(ScholarDto p) { if (string.IsNullOrEmpty(p.BookId)) { return this.Jsonp(new { Success = 0, Msg = "查詢失敗:" + ":前台傳參異常" }); } var list = new List<ScholarDto>();//學者集合列表 var groups = new List<ScholarDto>();//學者研究主題集合列表 try { list=scholarService.GetScholarRelation(p); var group=list.GroupBy(c => c.GroupId); foreach (var item in group) { groups.Add(new ScholarDto(){ GroupId=item.Key??0,GroupName=item.FirstOrDefault().GroupName}); } return this.Jsonp(new { Success = 1, Msg = "查詢成功", List = list, Group = groups }); } catch (Exception ex) { return this.Jsonp(new { Success = 0, Msg = "查詢失敗:" + ex.Message }); } } #endregion
public partial class xk_scholar { public long Id { get; set; } public string BookId { get; set; } public string RealName { get; set; } public Nullable<long> GroupId { get; set; } public string Avatar { get; set; } public string Link { get; set; } public string Editor { get; set; } public Nullable<int> OrderNum { get; set; } public Nullable<System.DateTime> ADDTIME { get; set; } public Nullable<System.DateTime> UpdateTime { get; set; } public Nullable<int> IsDel { get; set; } }
public class ScholarDto : xk_scholar { /// <summary> /// 研究主題名稱 /// </summary> public string GroupName { get; set; } /// <summary> /// 重新編碼排序的研究主題編號,從1開始,用以使用插件echarts /// </summary> public int GroupCode { get; set; } }
前台腳本,控制圖表顯示與隱藏
$(function () { var curGroupId=@(ViewBag.GroupId??0); if (curGroupId>0) {//通過左側導航點擊 $(".choose a[data-groupid='{0}']".format(curGroupId)).click(); } else {//默認第一條顯示 $(".choose a:eq(0)").click(); } init_ready();//調整高度 })
總結
切換分類,展示不同的ECharts,可以采用實例化多個ECharts,腳本控制圖表的顯示與隱藏。在script標簽里,使用razor視圖模板語法,在C#代碼里輸出js代碼,使用<text></text>標簽即可。