js代码
function GetOrganization() {
var data = "";
var myChartOrganization = echarts.init(document.getElementById('divOrganization'));
var labelOption = {
normal: {
show: true,
formatter: '{c} {name|{a}}',
fontSize: 16,
rich: {
name: {
textBorderColor: '#fff'
}
}
}
};
// 指定图表的配置项和数据
var option2 = {
graphic: [
{
type: 'image',
id: 'logo',
bounding: 'raw',
style: {
image: '../image/background3.jpg',
width: 1545,
}
}
],
series: [
{
type: 'tree',
data: [data],
left: '2%',
right: '2%',
top: '8%',
bottom: '20%',
symbol: 'image://http://' + window.location.host + '/image/Dark_blue_button.png',//'emptyCircle',
symbolSize: [100, 30],
orient: 'vertical',
expandAndCollapse: false,
initialTreeDeptp:-1,
itemStyle: {
color: '#f56954',
borderColor: "#00c0ef",
borderWidth:8,
},
label: {
formatter: '{b} ',
position: 'inside',
distance:5,
fontSize: 14,
color:"#FFF",
},
leaves: {
label: {
position: 'inside',
// rotate: -90,
verticalAlign: 'middle',
align: 'center',
},
itemStyle: {
color:"#00c0ef",
}
},
animationDurationUpdate: 750
}
] // color: ['#007bff', '#dc3545','#2E90CD', '#FE0000']
};
// 使用刚指定的配置项和数据显示图表。
myChartOrganization.showLoading(); // 加载动画
myChartOrganization.setOption(option2);
myChartOrganization.hideLoading();
GetChartResult();
function GetChartResult() {
var ID = '1000';
var ParentID = '0';
var auto = myChartOrganization.getOption();
$.ajax({
type: 'POST',
url: '@Url.Action("GetOrganization","BaseData")',
//contentType: "application/json; charset=utf-8",
data: {
ID: ID,
ParentID:ParentID,
},
async: false,
dataType: "json",
success: function (data) {
//console.log(data)
var auto = myChartOrganization.getOption();
var data1 = data.replace(/ID/g, "value").replace(/OrganizationName/g, "name").replace(/CHILDREN/g, "children")
var data2 = data1.substring(0, data1.length - 1);
var data3 = data2.substring( 1,data1.length);
var objData = JSON.parse(data1)
auto.series[0].data = objData; //数据源
//auto.legend.data =legendData;
myChartOrganization.showLoading(); // 加载动画
myChartOrganization.setOption(auto, false);
myChartOrganization.hideLoading();
myChartOrganization.on('click', function (params) {
console.log('params')
console.log(params)
var name = params.name;
var seriesType = params.seriesType;
console.log(name + "\n" + seriesType);
if (params.data.children.length == 0) {
$('#txtBelongOrganizationID').val(params.value);
$('#txtBelongOrganizationName').val(params.name);
$('#' + SelectOrganizationID_ID).val($('#txtBelongOrganizationID').val());
$('#' + SelectOrganizationName_ID).val($('#txtBelongOrganizationName').val());
}
else {
$('#txtBelongOrganizationID').val('');
$('#txtBelongOrganizationName').val('');
$('#' + SelectOrganizationID_ID).val($('#txtBelongOrganizationID').val());
$('#' + SelectOrganizationName_ID).val($('#txtBelongOrganizationName').val());
}
$('#' + SelectOrganizationID_ID).trigger("change");
})
},
error: function (message) {
// alert(message);
}
});
}
}
MVC controller代码
public JsonResult GetOrganization(OrganizationModels om)
{
var resultmodel = new ResultModel<object>();
try
{
DataTable dt = Organizations.GetOrganization(om);
List<OrganizationModels> ls = DataTableExtend.ToDataList<OrganizationModels>(dt);
string org = JsonConvert.SerializeObject(OrganizationModels.OrganizationRecursion(om.ParentID, ls));
return Json(org);
}
catch (MySqlException ex)
{
resultmodel.ErrorCode = "1";
resultmodel.Message = ex.Message;
return Json(resultmodel);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace com.aaa.Models
{
public class OrganizationModels
{
public string ID { get; set; }
public string OrganizationName { get; set; }
public string ParentID { get; set; }
public List<OrganizationModels> CHILDREN { get; set; }
public static List<OrganizationModels> OrganizationRecursion(string pid, List<OrganizationModels> obj)
{
List<OrganizationModels> lso = new List<OrganizationModels>();
for (int i = 0; i < obj.Count; i++)
{
OrganizationModels om = new OrganizationModels();
if (obj[i].ParentID == pid)
{
om.ID = obj[i].ID;
om.ParentID = obj[i].ParentID;
om.OrganizationName = obj[i].OrganizationName;
lso.Add(om);
om.CHILDREN = OrganizationRecursion(obj[i].ID, obj);
}
}
return lso;
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace com.aaa.Extend
{
/// <summary>
/// DataTable扩展方法类
/// </summary>
public static class DataTableExtend
{
/// <summary>
/// DataTable转成List
/// </summary>
public static List<T> ToDataList<T>(this DataTable dt)
{
var list = new List<T>();
var plist = new List<PropertyInfo>(typeof(T).GetProperties());
if (dt == null || dt.Rows.Count == 0)
{
return null;
}
foreach (DataRow item in dt.Rows)
{
T s = Activator.CreateInstance<T>();
for (int i = 0; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
try
{
if (!Convert.IsDBNull(item[i]))
{
object v = null;
if (info.PropertyType.ToString().Contains("System.Nullable"))
{
v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
}
else
{
v = Convert.ChangeType(item[i], info.PropertyType);
}
info.SetValue(s, v, null);
}
}
catch (Exception ex)
{
throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
}
}
}
list.Add(s);
}
return list;
}
/// <summary>
/// DataTable转成实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static T ToDataEntity<T>(this DataTable dt)
{
T s = Activator.CreateInstance<T>();
if (dt == null || dt.Rows.Count == 0)
{
return default(T);
}
var plist = new List<PropertyInfo>(typeof(T).GetProperties());
for (int i = 0; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
try
{
if (!Convert.IsDBNull(dt.Rows[0][i]))
{
object v = null;
if (info.PropertyType.ToString().Contains("System.Nullable"))
{
v = Convert.ChangeType(dt.Rows[0][i], Nullable.GetUnderlyingType(info.PropertyType));
}
else
{
v = Convert.ChangeType(dt.Rows[0][i], info.PropertyType);
}
info.SetValue(s, v, null);
}
}
catch (Exception ex)
{
throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
}
}
}
return s;
}
/// <summary>
/// List转成DataTable
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entities">实体集合</param>
public static DataTable ToDataTable<T>(List<T> entities)
{
if (entities == null || entities.Count == 0)
{
return null;
}
var result = CreateTable<T>();
FillData(result, entities);
return result;
}
/// <summary>
/// 创建表
/// </summary>
private static DataTable CreateTable<T>()
{
var result = new DataTable();
var type = typeof(T);
foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
var propertyType = property.PropertyType;
if ((propertyType.IsGenericType) && (propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
propertyType = propertyType.GetGenericArguments()[0];
result.Columns.Add(property.Name, propertyType);
}
return result;
}
/// <summary>
/// 填充数据
/// </summary>
private static void FillData<T>(DataTable dt, IEnumerable<T> entities)
{
foreach (var entity in entities)
{
dt.Rows.Add(CreateRow(dt, entity));
}
}
/// <summary>
/// 创建行
/// </summary>
private static DataRow CreateRow<T>(DataTable dt, T entity)
{
DataRow row = dt.NewRow();
var type = typeof(T);
foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
row[property.Name] = property.GetValue(entity) ?? DBNull.Value;
}
return row;
}
}
}
数据库查询语句
public static DataTable GetGoodOneOrganization(OrganizationModels om)
{
string sqlstr = @" SELECT DepartmentID AS ID,DepartmentName AS OrganizationName,ParentDepartmentID AS ParentID FROM
(
SELECT DepartmentID , ParentDepartmentID,DepartmentName
FROM t_department
WHERE ParentDepartmentID IS NOT NULL
) rd,(SELECT @pid := @ID) pd
WHERE FIND_IN_SET( ParentDepartmentID, @pid ) > 0 AND @pid := concat( @pid, ',', DepartmentID ); ";
MySqlParameter[] sqlParameter = new MySqlParameter[] {
new MySqlParameter("ID",om.ID),
};
DataTable dt = MySqlHelper_.ExecuteDataTable(MySqlHelper_.GoodOneconnstr, sqlstr, sqlParameter);
return dt;
}
数据库内容
echarts展示效果