从递归模型创建表单 [英] Create a form from a recursive model
问题描述
我有一个递归模式是这样的:
公共类节点
{
公众诠释标识{搞定;组; }
公共字符串文本{搞定;组; }
公众的IList<节点>蔡尔兹{搞定;组; } 公共节点()
{
蔡尔兹=新的List<节点>();
}
}
我建立与它一棵树使用该code withing剃刀观点:
< UL>
@DisplayNode(型号)
< / UL>@helper DisplayNode(节点节点){
<立GT;
@ node.Text @if(node.Childs.Any())
{
< UL>
@foreach(VAR孩子node.Childs)
{
@DisplayNode(子)
}
< / UL>
}
< /李>
}
一切正常,我的树渲染,但我需要在树上的每一行添加一个文本框,我希望有这样的输入名称:
童车[0] .Childs [1] .Childs [2]。文本
所以我的模型绑定将正常工作。
有没有办法通过使用EditorTemplates或其他任何东西来实现这一目标?
我想避免的形式在JavaScript构建输入名称提交。
您可以使用它尊重当前的导航方面,而不是如 @helper
所以定义为节点
键入(自定义编辑器模板〜/查看/共享/ EditorTemplates / Node.cshtml
)
@model节点
<立GT;
@ Html.LabelFor(X => x.Text)
@ Html.EditorFor(X => x.Text)
@if(Model.Childs.Any())
{
< UL>
@ Html.EditorFor(X => x.Childs)
< / UL>
}
< /李>
,然后里面的一些主视图:
@model MyViewModel
< UL>
@ Html.EditorFor(X => x.Menu)
< / UL>
其中菜单
属性的类型显然节点
。
I have a recursive model like this:
public class Node
{
public int Id { get; set; }
public string Text { get; set; }
public IList<Node> Childs { get; set; }
public Node()
{
Childs = new List<Node>();
}
}
I am building a tree with it withing a razor view by using this code:
<ul>
@DisplayNode(Model)
</ul>
@helper DisplayNode(Node node) {
<li>
@node.Text
@if(node.Childs.Any())
{
<ul>
@foreach(var child in node.Childs)
{
@DisplayNode(child)
}
</ul>
}
</li>
}
Everything works fine, my tree renders, but I need to add a textbox on each row of the tree and I want to have to input names like this:
Childs[0].Childs[1].Childs[2].Text
So my model binding will work as expected.
Is there any way by using EditorTemplates or anything else to achieve this?
I want to avoid building input names in javascript on the form submit.
You could use editor templates which respect the current navigational context instead of such @helper
.
So define a custom editor template for the Node
type ( ~/Views/Shared/EditorTemplates/Node.cshtml
):
@model Node
<li>
@Html.LabelFor(x => x.Text)
@Html.EditorFor(x => x.Text)
@if (Model.Childs.Any())
{
<ul>
@Html.EditorFor(x => x.Childs)
</ul>
}
</li>
and then inside some main view:
@model MyViewModel
<ul>
@Html.EditorFor(x => x.Menu)
</ul>
where the Menu
property is obviously of type Node
.
这篇关于从递归模型创建表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!