openflashchart是比较好的报表组件,曾经在ASP.NET项目中多次使用。在ASP.NET开发中,大家都习惯了使用控件。对于一些项目要求不高或者团队成员水平相对比较弱的项目,控件是可以提高生产效率和代码质量的。但这次环境是在MVC2中,在网上找来下,发现只有ASP.NET版本的源码,没有MVC的源码。没办法只有自己封装了。其实封装也没有那么难。具体见下:
ASP.NET页面代码
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "550", "200","9.0.0", "expressInstall.swf",{"data-file":"datafile/glassbar.aspx"});
</script>
上面是demo中,页面的代码。需要对上面的代码进行封装具体见下面步骤:
第一步,实现对htmlhelper的扩展:
public static class OpenflashChartHelper
{
public static string OpenflashChart(this HtmlHelper helper, OpenFlashChart.OpenFlashChart chart, string height, string width)
{
//设置参数数组
string keyId = "a_" + System.Guid.NewGuid().ToString();
string controller = "Report";
string action = "ReportJson";
object[] parms = new object[] { keyId, height, width, controller, action, "{", "}" };
//组装脚本段
string scriptStr = string.Format(@"
<script type=""text/javascript"">
swfobject.embedSWF(""/Content/open-flash-chart.swf"", ""{0}"", ""{1}"", ""{2}"",""9.0.0"", ""expressInstall.swf"",{5}""data-file"":""/{3}/{4}/{0}""{6});
</script><div class=""ReportChartStyle"" id=""{0}""></div>", parms);
HttpContext.Current.Cache[keyId] = chart.ToPrettyString();
return scriptStr;
}
}
第二步,实现ReportController的处理方法:
public class ReportController : Controller
{
/// <summary>
/// 获取缓存中对应的JSON数据串
/// </summary>
/// <param name=\"id\">缓存GUID键值</param>
/// <returns>JSON数据</returns>
public string ReportJson(string id)
{
if (HttpContext.Cache[id] != null)
{
string temp = (string)(HttpContext.Cache[id]);
HttpContext.Cache.Remove(id);
return temp;
}
//当缓存中没有数据时,这个场景是用户后退时情况下会发生,构造一个空的JSON数据返回
return "{\"title\": {\"text\": \"报表已经失效或过期,请刷新页面\",\"style\": \"{font-size: 20px; color:#0000ff; font-family: Verdana; text-align: center;}\"},\"x_axis\": {\"labels\": {},\"steps\": 1,\"3d\": 0,\"offset\": true},\"y_axis\": {\"tick-length\": 0,\"labels\": {},\"3d\": 0,\"offset\": true},\"elements\": [{\"colours\": [\"FF0000\"],\"border\": 2,\"alpha\": 0.5,\"animate\": [{\"type\": \"bounce\",\"distance\": 5}],\"start-angle\": 0,\"colour\": \"#CC3399\",\"tip\": \"#label# \\u8BBF\\u95EE\\u6B21\\u6570#val# \\u6240\\u5360\\u767E\\u5206\\u6BD4\\uFF1A#percent#\",\"values\": [{\"value\": 0,\"label\": \"\\u5176\\u4ED6\"}],\"font-size\": 14,\"fill-alpha\": 0.35,\"type\": \"pie\",\"dot-style\": {\"on-show\": {}}}],\"bg_colour\": \"#FFFFFF\"}";
}
}
页面上应用
<%=Html.OpenflashChart(Model, "500", "500") %>
在View中使用的Model需要是OpenFlashChart类型,具体业务场景就需要自己在业务中来写了。详细的就不说了。
ASP.NET页面代码