echarts 在.net 中和数据库交互

  需求描述: 在FineUIMVC中加载图形控件echarts 其官网中只有静态的json语句的数据源,没有关于取数据库的资料,几天下午百度了一些方法。坑太多了, 但是 只要方向没错, 总有成功的方法:

 1.起初从简单的Webform 中处理开始(思路:从数据库中取数据保留在datatable 中, 再把datatable 转成json 格式的数据 ; ajax 怎样和后台交互:(通过一般处理程序.ashx 向js中异步传所需的数据)

 2.先贴些代码:

一下是.ashx 代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Serialization;

namespace WebApplication1
{
/// <summary>
/// Test01 的摘要说明
/// </summary>
public class Test01 : IHttpHandler
{
/// <summary>
/// 您将需要在网站的 Web.config 文件中配置此处理程序
/// 并向 IIS 注册它,然后才能使用它。有关详细信息,
/// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
/// </summary>
#region IHttpHandler Members
SqlConnection con = new SqlConnection("Server=.;User Id=sa;Pwd=123456;DataBase=AppBoxMvc");
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
JavaScriptSerializer jsS = new JavaScriptSerializer();
List<object> lists = new List<object>();
//Series seriesObj = new Series();
string result = "";

public void ProcessRequest(HttpContext context)
{
//获取一同发送过来的参数
//string command = context.Request["cmd"];
context.Response.ContentType = "text/plain";
//用来传回去的内容
//context.Response.Write("Hello World");
Get_Data01(context);
}

public void Get_Data01(HttpContext context)
{
string sql = @"SELECT Name, ParentID FROM dbo.Menus WHERE ParentID IS NOT null and ParentID <> 1";
ds = GetDataFromDatabase(sql);
lists = new List<object>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
var obj = new { Name = dr["Name"], ParentID = dr["ParentID"] };
lists.Add(obj);
}
jsS = new JavaScriptSerializer();
result = jsS.Serialize(lists);
context.Response.Write(result);
}

public DataSet GetDataFromDatabase(string sql)
{
ds = new DataSet();
adapter = new SqlDataAdapter(sql, con);
adapter.Fill(ds);
return ds;
}

public bool IsReusable
{
// 如果无法为其他请求重用托管处理程序,则返回 false。
// 如果按请求保留某些状态信息,则通常这将为 false。
get { return false; }
}


#endregion
}
}

以上代码返回web调用的数据源。

前端代码:

一,添加 js引用

<!-- 引入 echarts.js -->
<script src="echarts.js"></script>

--- jquery 库
<script src="jquery-1.11.1.js"></script>

二,拼接动态字符串

var name = '[';

name += 'transresult[' + item + '].Name' + ', ';

name += ']';

三,取动态字符串的值

--eval 函数

eval(name);

四, 完整代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>


<title>ECharts</title>
<!-- 引入 echarts.js -->
<script src="echarts.js"></script>
<script src="jquery-1.11.1.js"></script>
</head>
<body>

<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main1" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例

var myChart1 = echarts.init(document.getElementById('main1'));

// 指定图表的配置项和数据
var option1 = {
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
title: {
text: '',
subtext: '',
},
legend: {
data: ['data'],
right: '5%'
},
grid: {
left: '5%',
right: '0%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: []
}
],

yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'New',
type: 'bar',
data: [100],
markPoint: {
data: [
{ type: 'max', name: 'Max Value' },
{ type: 'min', name: 'Min Value' }
]
},
},
]
};


$.ajax({
type: "post",
async: false,
url: "Test01.ashx",

datatype: "json",
success: function (result) {
if (result) {

eval("var transresult=" + result);

var name = '[';
var parentId = '[';
for (var item in transresult)
{
if (item < transresult.length - 1) {
name += 'transresult[' + item + '].Name' + ', ';
parentId += 'transresult['+item+'].ParentID' + ', ';
}
else {
name += 'transresult[' + item + '].Name' ;
parentId += 'transresult[' + item + '].ParentID' ;
}
}
//}
name += ']';
parentId += ']';
option1.xAxis[0].data = eval(name);
option1.series[0].data = eval(parentId);
alert(name);
alert(option1.series[0].data);
myChart1.setOption(option1);
}
},
error: function (errorMsg) {
alert(errorMsg);
}
});
// 使用刚指定的配置项和数据显示图表。

</script>

</body>
</html>

--------------------------------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------------------------

FINEUIMVC 中的测试。

是否可以使用一般窗体:(可以,但需要修改Web.config 中添加以下内容)

<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>

然后按正常的控制器视图模式就可以生成类型webform的程序

如果是正常的.cshtml 文件如果能在JS 代码里处理一般处理过程,则其加载数据的方式 和 webform无异。

在测试环境中是成功的!

 

posted @ 2017-09-04 18:52  hzf08  阅读(1493)  评论(0编辑  收藏  举报