如何绑定随机计数列



如何将这个(dynamic)表绑定到IList<IList<string>>或其他类型

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"/>
}

我需要得到列和行

更新:

也许我可以取String[][]

我的第一个想法是使用Dictionary<string, string>,但这是不可索引的,所以你必须写一个自定义模型绑定器。没有那么难,但仍然。然后我想使用List<KeyValuePair<string, string>>,但KeyValuePair有私人设置,所以,再一次,你需要一个自定义的粘合剂。所以我认为最好的方法是:

创建自定义类型

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

现在,将这种类型的列表作为属性添加到视图模型

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

当然,在填充列表和强类型键入视图之后,您可以使用内置的html helper来呈现表,以确保模型绑定不会出现任何问题

@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>
            }     

然后在控制器中捕获模型并访问您的数据

        [HttpPost]
        public ActionResult Index(Model viewModel)
        {
            foreach (var item in viewModel.MyItems)
            {
                string columnOneValue = viewModel.MyItems[0].Key;
                string columnTwoValue = viewModel.MyItems[0].Value; 
            }

最新更新