[英]How to implement a simple TreeView using ASP.NET MVC
我是web開發的新手,想用VS2019搭建一個非常簡單的網站,基於MVC結構。 我需要在網頁中創建一個 treeview,節點可選,盡可能簡單。
我加載數據沒有問題,填充到任何結構/class。 但是,我不知道如何在網頁中顯示 treeview。
我已經找了四個小時了。 我在NuGet中看到很多js樹插件,很多TreeView controller。 我只想要一個簡單的樹,最好來自微軟而不是任何其他第三方。 我看到一個 TreeView WebControl 但它似乎適用於 Web 表單應用程序 (.aspx)。
請不要告訴我搜索互聯網,因為我真的很努力,非常努力。 非常感謝!
如果在cshtml中使用的不是微軟開箱即用的,請確認,我將停止搜索,如果可能,請推薦一種最容易學習和使用的TreeView的使用方式。
jstree / Telerik /???
托尼,我也一直在尋找同樣的東西。 You are right, there is a TreeView for ASP.NET Core, but it's for Windows Forms and not web pages:
我還查看了 Telerik 和 Syncfusion,但我試圖避免為解決方案付費。
首先,對於數據結構,我確實在這里找到了 David West 編寫的名為 TreeCollections 的 NuGet package:
https://github.com/davidwest/TreeCollections
我已經實現了這一點,並且可以從我的數據中成功構建一個或多個層次樹。 你可能想看看你的樹數據結構。
現在要在 web 頁面上顯示數據,我認為微軟沒有任何工具可以幫助我們。 我像你一樣搜索過。 您提到JsTree ,我認為這是一個可行的選擇,但它不是您指定的僅 html。 我認為我們至少必須使用一些 javascript。
這里有兩個很好的 JSTree 延遲加載實現: 在 Asp.Net MVC 中使用 JsTree 延遲加載 TreeView
根據樹的大小和深度,如果您可以在用戶導航樹時動態提取數據,這可能是最佳解決方案。 如果您想首先將數據預加載到樹結構中,就像我對 TreeCollections 所做的那樣,那么填充結構可能會起作用,但如果您想以交互方式顯示/隱藏樹上的分支,它仍然需要 javascript 的幫助.
更新:我能夠使用jsTree在我的 web 頁面上加載和顯示分層樹,代碼很少。 我發現我根本不需要 TreeCollections。 首先,保存每個節點數據的 model:
public class JsTreeModel
{
public string id { get; set; }
public string parent { get; set; }
public string text { get; set; }
public string icon { get; set; }
public string state { get; set; }
public bool opened { get; set; }
public bool disabled { get; set; }
public bool selected { get; set; }
public string li_attr { get; set; }
public string a_attr { get; set; }
}
這是我將數據加載到列表中的代碼。 我在 ASP.Net Core 3.1 中工作,所以我使用 System.Text.Json 來序列化數據。 首先將數據庫中的數據檢索到項目列表<>中,不需要排序。 然后:
using System.Text.Json;
[...]
IList<JsTreeModel> nodes = new List<JsTreeModel>();
foreach (var item in items)
{
nodes.Add(new JsTreeModel
{
id = item.Id.ToString(),
parent = item.ParentId == null ? "#" : item.ParentId.ToString(),
text = item.Name
});
}
//Serialize to JSON string.
ViewBag.Json = JsonSerializer.Serialize(nodes);
return View();
然后在您看來,您只需要一個包含樹的 div:
<div id="jstree"></div>
這個 javascript 將填充它:
<script type="text/javascript">
$(document).ready(function () {
$('#jstree').jstree({
"core" : {
"data" : @Html.Raw(ViewBag.Json)
}
});
});
</script>
jsTree 將 go 通過 Json 數據創建一個 ul 結構並將其放入 div 中。 很容易!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.