之前easyUI的Tree插件的数据是通过tree_data.json把静态数据加载进来的,苦于技术浅薄尚未研究出从数据库加载动态数据,今天终于用MVC+Linq捣鼓出来了,故记录下来以便日后翻看。
代码如下:
Global.asax.cs:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Application["WebPath"] = System.Web.HttpContext.Current.Request.ApplicationPath.EndsWith("/") ? System.Web.HttpContext.Current.Request.ApplicationPath : System.Web.HttpContext.Current.Request.ApplicationPath + "/";
}
aspx:
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" type="text/css" href="<%=Application["WebPath"] %>Themes/default/easyui.css" />
<link rel="stylesheet" type="text/css" href="<%=Application["WebPath"] %>Themes/icon.css" />
<link rel="stylesheet" type="text/css" href="<%=Application["WebPath"] %>Themes/StyleSheet.css" />
<script type="text/javascript" src="<%=Application["WebPath"] %>Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="<%=Application["WebPath"] %>Scripts/json2.js"></script>
<script type="text/javascript" src="<%=Application["WebPath"] %>Scripts/jquery.easyui.min.js"></script>
<script type="text/javascript" src="<%=Application["WebPath"] %>Scripts/MyJQueryFunction.js"></script>
</head>
<body>
<div region="west" split="true" title="影视分类" style="width:200px;padding:10px;">
<ul id="tree"></ul>
</div>
</body>
</html>
MyJQueryFunction.js:
$(function () {
LoadTree();
});
function LoadTree() {
$('#tree').tree({
animate: true,
dnd: true,
url: '../Home/GetTreeViewData',
onlyLeafCheck: true,
onClick: function (node) {
$(this).tree('toggle', node.target);
if ($(this).tree('isLeaf', node.target)) {
opentab(node.text, node.id);
}
},
onContextMenu: function (e, node) {
e.preventDefault();
$('#tree').tree('select', node.target);
}
});
}
HomeController.cs:
VodDataClassesDataContext db = new VodDataClassesDataContext();
public class TreeView
{
public TreeView(int id, string text, string state, List<TreeView> children)
{
this.id = id;
this.text = text;
this.state = state;
this.children = children;
}
public int id { get; set; }
public string text { get; set; }
public string state { get; set; }
public List<TreeView> children { get; set; }
}
public JsonResult GetTreeViewData()
{
return Json(InitTree(0));
}
public List<TreeView> InitTree(int parentid)
{
var sql = db.TreeView.Where(T => T.ParentID.Equals(parentid)).Select(T => new TreeView
(
T.ID,
T.Text,
T.State,
InitTree(T.ID) //递归树子节点,妥!
));
if (sql.Count() > 0)
{
return sql.ToList<TreeView>();
}
else return null;
}
附上截图:
鼠标移到“影视名称”显示图片。