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?
有没有办法使用EditorTemplates或其他任何方法来实现这一目标?
I want to avoid building input names in javascript on the form submit.
我想避免在表单提交的javascript中构建输入名称。
1 个解决方案
#1
6
You could use editor templates which respect the current navigational context instead of such @helper
.
您可以使用尊重当前导航上下文的编辑器模板而不是@helper。
So define a custom editor template for the Node
type ( ~/Views/Shared/EditorTemplates/Node.cshtml
):
因此,为Node类型定义一个自定义编辑器模板(〜/ 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
.
其中Menu属性显然是Node类型。
#1
6
You could use editor templates which respect the current navigational context instead of such @helper
.
您可以使用尊重当前导航上下文的编辑器模板而不是@helper。
So define a custom editor template for the Node
type ( ~/Views/Shared/EditorTemplates/Node.cshtml
):
因此,为Node类型定义一个自定义编辑器模板(〜/ 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
.
其中Menu属性显然是Node类型。