本文主要在asp.net下面制作生成,利用到了JQuery中的Tree控件,采用的是asp.net中ICallbackEventHandler接口实现.
本方法比较简单,可以很方便的对一些逻辑要求不高的功能使用.具体生成页面如下:
然后就是本页面所用到的代码:
首先是前台页面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <script src="jquery.treeview/lib/jquery.js" type="text/javascript"></script> <script src="jquery.treeview/common.js" type="text/javascript"></script> <script src="jquery.treeview/jquery.tree.js" type="text/javascript"></script> <link href="jquery.treeview/tree.css" rel="stylesheet" type="text/css" /> <title>基于ICallbackEventHandler的轻量级ajax回调方法</title> <script type="text/javascript"> $(document).ready(function() { raiseEvent(); }); function rServer(arg, context) { var o = { showcheck: true }; //显示按钮 o.data = eval(arg); //处理json数据 $("#showTree").treeview(o); //绑定到树上 } function raiseEvent(arg, context) { <%=ClientScript.GetCallbackEventReference(this,"arg","rServer","context") %>; } </script> </head> <body> <form id="form1" runat="server"> <div id="showTree"> </div> </form> </body> </html>
需要说明的是raiseEvent方法和rServer方法,首先是raiseEvent方法发起对服务器端的ajax请求,请求的数据内容存在于arg参数中,然后传递到后台,而其中的代码
<%=ClientScript.GetCallbackEventReference(this,"arg","rServer","context") %>;
则是指明了rServer是回调成功后,所调用的方法.
后台代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
/*******************************************************
* 基于ICallbackEventHandler的轻量级ajax回调方法
* 使用方式:首先页面需要继承自ICallbackEventHandler接口
* 然后页面必须实现RaiseCallbackEvent和GetCallbackResult
* 方法,其中注意的是,前面一个函数先被调用,用来接收从前台
* 传送来的数据,后面一个函数是将处理过的函数返回到前台
* ****************************************************/
public partial class _Default : System.Web.UI.Page,ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string jsonStr = string.Empty;
public string GetJson()
{
string json = "[";
IList<Tree> t = DB.returnParentTree();
foreach (Tree model in t)
{
if (model != t[t.Count - 1])
{
json += GetJsonByModel(model) + ",";
}
else
{
json += GetJsonByModel(model);
}
}
json += "]";
json = json.Replace("'", "\"");
return json;
}
public string GetJsonByModel(Tree t)
{
string json = "";
bool flag = DB.isHaveChild(t.ModuleID);
json = "{"
+ "'id':'" + t.ModuleID + "',"
+ "'text':'" + t.ModuleName + "',"
+ "'value':'" + t.ModuleID + "',"
+ "'showcheck':true,"
+ "'checkstate':'0',"
+ "'hasChildren':" + flag.ToString().ToLower() + ","
+ "'isexpand':false,"
+ "'ChildNodes':";
if (!flag)
{
json += "null,";
json += "'complete':false}";
}
else
{
json += "[";
IList<Tree> list = DB.getChild(t.ModuleID);
foreach (Tree tree in list)
{
if (tree != list[list.Count - 1])
{
json += GetJsonByModel(tree) + ",";
}
else
{
json += GetJsonByModel(tree);
}
}
json += "],'complete':true}";
}
return json;
}
public string GetCallbackResult()
{
return jsonStr;
}
public void RaiseCallbackEvent(string eventArgument)
{
jsonStr = GetJson();
}
}