1. 程式人生 > >Extjs4.2 TreePanel+Asp.net mvc 動態載入節點

Extjs4.2 TreePanel+Asp.net mvc 動態載入節點

extjs經常使用的部分有介面、資料模型、資料來源、事件。構建TreePanel需要三個,UI、模型、和資料來源。

在extjs中,為了讓資料來源能夠正確載入資料,我們需要定義以個數據模型。

樹節點的模型定義:

Ext.define('TreeData', {
    extend: 'Ext.data.Model',
    fields: [
        { name: 'id', },
        { name: 'cls' },
        { name: 'leaf' },
        { name: 'text' },
    ]
});

一個節點有的幾個關鍵欄位,Id是唯一標識,在真個Treepanel中不能重複。cls是節點的圖示。leaf表示是否還有子節點。text節點顯示的名稱。

資料來源定義:

var treestore = new Ext.data.TreeStore({
            proxy: {
                type: 'ajax',
                url: '/tree/getnodes'
            },

            model: 'TreeData',
            root: {
                text: '目錄樹',
                id: 'root',
                expanded: true
            }
        })

建立treepanel:
        var treepanel=Ext.create('Ext.tree.Panel', {
            title: '目錄樹',
            renderTo : Ext.getBody(),
            width: 200,
            collapsible: true,   
            split: true,        
            store: treestore,
            rootVisible: false,
            useArrows: true
        });

後臺程式碼,我們採用的asp.net mvc 來實現:

    public class TreeController : Controller
    {
        public ActionResult GetNodes(string node)
        {
            List<object> result = new List<object>();
            if (node == "root")
            {
                result.Add(new
                {
                    cls = "devtree-folder",
                    id = "001",
                    qtip = "",
                    text = "測試1"
                });
            }
            else
            {
                //根據具體情況返回結果,可以是選單功能,也可以是資料庫查詢出來的資料。
                result.Add(new
                {
                    cls = "",
                    id = "001000",
                    qtip = "",
                    text = "資料1",
                    leaf = false
                });
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }

資料來源在非同步請求資料時,會將當前節點的id(node)傳到後臺。後臺根據具體需求情況返回符合規則的資料。