我已经把头发扯断了,所以我正在寻求帮助。我构建了一个简短的递归 HTML Helper 来显示列表列表。我想将任何编辑返回给控制器。一个孩子的孩子不断回来为空。当我删除递归并强制通过“for循环”的第二层时,它似乎有效。有什么线索吗?我即将在 RAZOR 上认输,只是学习在 Jquery 中完成所有这些......
根据我的代码,当模型被回发时,问题就出在这里(您将在 post ActionResult 方法的评论中看到这一点):
Node.Name 没问题
Node.Children[0].Name 没问题
Node.Children[1].Name 没问题
Node.Children[1].Children = null (这就是问题所在!)
控制器代码
public ActionResult Y()
{
Node driverTree = new Node() { Name="Level1", Children = new List<Node>() };
driverTree.Children.Add(new Node() { Children = null, Name = "Level2A" });
driverTree.Children.Add(new Node() {Name ="Level2B", Children = new List<Node> {new Node{Name="Level3A", Children=null},
new Node{Name="Level3B", Children=null}}
});
return View(driverTree);
}
[HttpPost]
public ActionResult Y(Node Node)
{
//Keeps returning:
// Node.Name is ok
// Node.Children[0].Name is ok
// Node.Children[1].Name is ok
// Node.Children[1].Children = null (HERE LIES THE PROBLEM!)
int x = 5; //
return View();
}
}
public class Node
{
public string Name { get; set; }
public List<Node> Children { get; set; }
public bool IsChecked { get; set; }
}
查看代码
@model JqueryUITests.Controllers.Node
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="../../Scripts/jquery-ui-1.10.3.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui.unobtrusive-2.1.0.min.js" type="text/javascript"></script>
}
@helper ShowTree(List<JqueryUITests.Controllers.Node> children)
{
<ul>
@for (int i = 0; i < children.Count;i++ )
{
<li>
@Html.EditorFor(x => children[i].Name)
@if (children[i].Children != null)
{
@ShowTree(children[i].Children)
}
</li>
}
</ul>
}
@using (Html.BeginForm())
{
<ul id="tree">
<li>
@Html.EditorFor(x=>Model.Name)
@ShowTree(Model.Children)
</li>
</ul>
<p>
<input type="submit" value="Create" />
</p>
}
代码
<form action="/X/Y" method="post"> <ul id="tree">
<li>
<input class="text-box single-line" id="Name" name="Name" type="text" value="Level1" />
<ul>
<li>
<input class="text-box single-line" id="children_0__Name" name="children[0].Name" type="text" value="Level2A" />
</li>
<li>
<input class="text-box single-line" id="children_1__Name" name="children[1].Name" type="text" value="Level2B" />
<ul>
<li>
<input class="text-box single-line" id="children_0__Name" name="children[0].Name" type="text" value="Level3A" />
</li>
<li>
<input class="text-box single-line" id="children_1__Name" name="children[1].Name" type="text" value="Level3B" />
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>
<input type="submit" value="Create" />
</p>