7

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.

Charles Ouellet
  • 6,338
  • 3
  • 41
  • 57

1 Answers1

6

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • @Darin how we can add node dynamically in this structure ? so that when we post form data to server default model binder map data in its right place – Gaurav Aug 14 '14 at 06:47
  • I had the same issue: a recursive object was giving me a "Stack Empty" exception in the EditorTemplate . I then tried the example in this question with this exact `Node` code and your suggested EditorTemplate. It still doesn't work for me. I get the same "Stack Empty" exception. – davidXYZ Feb 10 '15 at 15:30
  • Kudos to you Darin :) – Craig Hannon May 15 '15 at 14:22