从 MVC 视图更新树模型
本文关键字:模型 更新 视图 MVC | 更新日期: 2023-09-27 18:37:02
我想在MVC中创建一个简单的可拖动树。但是我无法了解如何将更改的集合返回到控制器。现在我总是有第一个模型,没有变化......
控制器:
public ActionResult Index()
{
TreeModel tree = new TreeModel();
tree.RootNodes = new List<TreeModel.Node>();
var root1 = new TreeModel.Node() { ID = 0, Name = "Root 1", NodeType = TreeModel.NodeType.Folder };
var root2 = new TreeModel.Node() { ID = 1, Name = "Root 2", NodeType = TreeModel.NodeType.Folder };
var node1 = new TreeModel.Node() { ID = 2, Name = "Node 1", NodeType = TreeModel.NodeType.Href };
var node2 = new TreeModel.Node() { ID = 3, Name = "Node 2", NodeType = TreeModel.NodeType.Href };
var folder1 = new TreeModel.Node() { ID = 4, Name = "Folder 1", NodeType = TreeModel.NodeType.Folder };
var folder2 = new TreeModel.Node() { ID = 5, Name = "Folder 2", NodeType = TreeModel.NodeType.Folder };
root1.Childs.AddRange(new[] { node1, folder1 });
root2.Childs.AddRange(new[] { node2, folder2 });
tree.RootNodes.AddRange(new[] { root1, root2 });
return View(tree);
}
[HttpPost]
public ActionResult Index(TreeModel tree)
{
string res = tree != null && tree.RootNodes != null ? "Success!" : "It is null...";
return Content(res);
}
型:
public class TreeModel
{
public List<Node> RootNodes { get; set; }
public enum NodeType
{
Href,
Folder
}
public class Node
{
public int ID { get; set; }
public string Name { get; set; }
public NodeType NodeType { get; set; }
private List<Node> _childs = new List<Node>();
public List<Node> Childs
{
get { return _childs; }
set { _childs = value; }
}
public override string ToString()
{
return string.Format("{0} - {1}", this.Name, this.NodeType);
}
}
}
视图:
@using DraggableTree.Models
@using DraggableTree.Helpers
@model TreeModel
@{
ViewBag.Title = "title";
Layout = null;
}
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
var target = $(event.target);
var newParent;
if (target.is("ul"))
newParent = target;
else
newParent = target.closest("li").children("ul");
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var draggedNode = document.getElementById(data);
newParent.append(draggedNode);
}
</script>
</head>
<h2>My Tree</h2>
@using (Html.BeginForm())
{
<ul ondrop="drop(event)">
@Html.EditorFor(m => m.RootNodes)
</ul>
<input type="submit"value="submit"/>
}
编辑器模板:
@using DraggableTree.Models
@using DraggableTree.Helpers
@model TreeModel.Node
<li draggable="true" id="@Model.ID" ondragover="allowDrop(event)" ondragstart="drag(event)">
<div class="node">
<b>@Model.NodeType @Html.EditorFor(m => m.Name)</b>
@Html.HiddenFor(m => m.ID)
</div>
<ul ondrop="drop(event)">
@Html.EditorFor(m => m.Childs)
</ul>
</li>
现在,我已经通过将属性ParentId
添加到 Node 模型并在删除操作中使用 jQuery 脚本对其进行更新来解决此问题。之后,在后期操作中,我必须重建我的树。(如果有人感兴趣 - 我可以发布代码)。
在博客上描述了我的最终解决方案。