Dean P
Dean P

Reputation: 2225

Razor view is not binding to controller expecting a model containing list of lists

I have a Model.

public class ViewInput
{
        public List<List<String>> cells;
        //Other stuff
}

This model data is passed to a Razor generated HTML view. Note that when the model is passed to the view, a tested and confirmed non-zero sized 2D list is passed to the view.

@model MvcMovie.Models.ViewInput

@*Stuff*@

@using (Html.BeginForm("GenerateDecisionTree", "Home", FormMethod.Post))
{
    <p>
            <table id="mainTable">

                @for (var i = 0; i < Model.cells.Count(); i++)
                {
                    <tr>
                        @for (var j = 0; j < Model.cells[i].Count(); j++)
                        {
                            <td>
                                @Html.TextBoxFor(m => m.cells[i][j])
                            </td>
                        }
                    </tr>
                }
            </table>
        </p>
    <div>
        <br><input type="submit" name="submit" class="btn btn-danger" value="Generate Decision Tree" />
    </div>
}

after which a post is handled by a controller

    [HttpPost]
    public String GenerateDecisionTree(ViewInput vi)
    {
        var test = vi.cells[0][0];//EXCEPTION - THE 2D LIST IS
        return "Hi There";
    }

Running this code results in an exception on the very first line of the controller code because the list of lists, called "cell", is empty for some reason. It should not be empty because we are posting data on a non zero 2D list.

I am well aware of this post and this link but they dont seem to answer my question.

Can any body please help me solve this problem

Upvotes: 0

Views: 41

Answers (1)

Yiyi You
Yiyi You

Reputation: 18209

You need to add get;set; to cells:

public class ViewInput
{
        public List<List<string>> cells { get; set; }
        //Other stuff
}

result: enter image description here

Upvotes: 1

Related Questions