邮政形式MVC与目录列表 [英] Post Form MVC with List of List

查看:120
本文介绍了邮政形式MVC与目录列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大部分的教程,问​​题我在网上找到有关的地方时,该模型具有项目之一名单。但对我来说我有一个项目列表进一步有一个项目列表。

Most of the Tutorials, Questions I found online where about when the Model has one List of Items. But In my Case I have a List of Items which further have a List of Items.

我有一个视图模型与意达意达的名单一览ItemsB

I have a ViewModel with List of ItemA, and ItemA has a list of ItemsB

 public class ViewModel
    {
        List<ItemA> Items { get; set; }

        public ViewModel()
        {
            Items = new List<ItemA>();
        }
    }

    public class ItemA
    {
        public int ItemAId { get; set; }
        public List<ItemB> ItemBList { get; set; }

        public ItemA()
        {
            ItemBList = new List<ItemB>();
        }
    }

    public class ItemB
    {
        public int ItemBId { get; set; }

// Need to input this string for each Item in List<ItemA>
        public string NewInput 

    }

我的观点:

@Html.BeginForm(){

@foreach (var itemA in Model.Items)
{
    <p>@itemA.ItemAId</p>


    for (int i = 0; i < itemA.ItemBList.Count; i++)
    {
        @Html.HiddenFor(m => itemA.ItemBList[i].ItemBId )

        @Html.TextBoxFor(m => itemA.ItemBList[i].NewInput)

    }
<button type="submit">Submit</button>
}

}

我的控制器:

public ActionResult SaveInfo(ViewModel model){
// Update
}

我的问题是我怎么写这种情况下,形式,以便它绑定回视图模型在控制器?

My Question is how do I write a Form for this Case so it binds back to ViewModel in Controller?

推荐答案

它相当简单 - 你只需要2窝在视图中环路(不要使用的foreach)

Its fairly simple - you just need to nest 2 for loops in the view (don't use foreach)

即更改为:

@Html.BeginForm(){

@for(int j = 0; j < Model.Items.Count; j++)
{
    <p>@Model.Items[j].ItemAId</p>
    @Html.HiddenFor(m => m.Items[j].ItemAId)  
    @* (don't forget this!) *@


    for (int i = 0; i < Model.Items[j].ItemBList.Count; i++)
    {
        @Html.HiddenFor(m => m.Items[j].ItemBList[i].ItemBId )

        @Html.TextBoxFor(m => m.Items[j].ItemBList[i].NewInput)

    }

}
<button type="submit">Submit</button>
}

MVC模式活页夹,需要的表单字段重新presenting特性列表中的被命名为类似 [#]。property1name [# ] .property2name ,以便回发后绑定期间妥善其关联到对方。同样的原则也适用于列出listItems中的性能。你需要使用一个循环而不是一个的foreach 循环得到正确的表单字段名称在使用HTML佣工!

The MVC Model Binder requires form fields representing properties in lists to be named something like [#].property1name, [#].property2name in order to properly associate them to each other during binding after postback. Same principle applies to list properties of listitems. You need to use a for loop rather than a foreach loop to get the right form field names when using HTML helpers!

这篇关于邮政形式MVC与目录列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆