0

How binding this (dynamic) table to IList<IList<string>> or another type

html:

@using (Html.BeginForm())
{
    <table>
        <thead>
            <tr><th>column1</th><th>column2</th></tr>
        </thead>
        <tbody>
            @for (int i = 0; i < 10; i++)
            {
                <tr><td><input type="text" value="@i" name="column1_@(i)"/></td><td><input type="text" value="@(Guid.NewGuid())" name="column2_@(i)"/></td></tr>
            }
        </tbody>
    </table>
    <input type="submit" value ="send"/>
}

I need get columns and rows

Update:

maybe I can take String[][]

Mediator
  • 14,951
  • 35
  • 113
  • 191

1 Answers1

0

My first thought was to use a Dictionary<string, string>, but that's not indexable, so you'd have to write a custom model binder. Not that hard, but still. Then I thought about using a List<KeyValuePair<string, string>>, but KeyValuePairs have private setters, so, again, you'd need a custom binder. So I think the best way is:

Create a custom type

public class MyItems
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }

Now, add a list of this type as a property to your view model

public List<MyItems> MyItems  { get; set; }

And, after populating the list and strongly typing your view, of course, you can render your table using the built in html helpers to ensure model binding won't have any hiccups

@for (int i = 0; i < Model.MyItems.Count( ); i++ )
            {
                <tr>
                    <td>@Html.TextBoxFor( m => m.MyItems[i].Key )</td>
                    <td>@Html.TextBoxFor( m => m.MyItems[i].Value)</td>
                </tr>
            }     

Then catch the model in the controller and access you data

        [HttpPost]
        public ActionResult Index(Model viewModel)
        {
            foreach (var item in viewModel.MyItems)
            {
                string columnOneValue = viewModel.MyItems[0].Key;
                string columnTwoValue = viewModel.MyItems[0].Value; 
            }
Forty-Two
  • 7,535
  • 2
  • 37
  • 54