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>