首页 文章

MVC4如何将模型属性列表从视图传递给Action

提问于
浏览
0

我试图将一个带有list属性的模型从视图传递到post操作 . 列表在帖子上返回null,但我们需要包含新项目的列表来更新其信息 . 我的模型看起来像这样:

public class Person()
    {
    internal string Name {get;set;}
    internal decimal Age {get;set;}
    internal List<int> Rate {get;set;}
    }

视图将填充其当前信息,我们使用foreach迭代列表,并为编辑功能生成文本框 . 当人员在编辑所需值后命中提交时,视图将转到[HttpPost]操作,但值为空 .

视图被@using(Html.BeginForm(Model))包围,在提交时,模型被传递给post动作,但列表为null . 填充所有其他值 .

有任何想法吗?附:我们正在使用c#和Razor View Engine对不起,但列表仍未传递给模型,这里是4循环 .

@{ int i = 0;}
        <table>
        @for (i = 0; i < Model.VendorContracts.Count; i++ )
        {

            if (i == 0)
            {
                    <tr>
                        <th>
                            Vendor Contracts
                        </th>
                        <th>
                        Effective Date
                        </th>
                    </tr>

            }
            if (i < 5)
            {
                <tr>
                    <td>@Model.VendorContracts[i]
                    </td>

                    <td>@Html.TextBoxFor(model => model.EffectiveDates[i])</td>
                </tr>
            }
            if (i == 5 || i == 10 || i == 15 || i == 20)
            {
                @:</table>
                @:<table>
                }
            if (i >= 5)
            {
                if (i == 5 || i == 10 || i == 15 || i == 20)
                {
                <tr>
                <th>Vendor Contracts
                </th>
                <th>
                Effective Date
                </th>
                </tr>
                }
            <tr>
            <td>
            @Model.VendorContracts[i]
            </td>
            <td>@Html.TextBoxFor(model => model.EffectiveDates[i])</td>
            </tr>
            }
        } 
        </table>

2 回答

  • 1

    我可以给你一个部分答案 . 要加载列表项,以便在HttpPost上返回它们,您需要在视图中执行此操作

    for(int idx = 0;idx < Model.Rate.Count;idx++)
    {
        @Html.TextBox("Foo", Model.Rate[idx])
    }
    

    关键思路是 @Html.TextBox("Foo", Model.Rate[idx]) ,在引用Rate列表项时必须使用索引器 . 这样,当您回发时,MVC模型 Binders 将能够获取列表项,包括对这些项的任何更改 .

    至于拿起用户添加的新项目,我不确定 . 也许其他SO用户可以提供帮助?但希望我的回答有所帮助 .

  • 0

    问题出在你的 foreach 循环上 . 您应该将其更改为 for 循环,并且绑定应该正常工作 .

    检查这些类似的问题和答案:

    ASP.NET MVC 4 - for loop posts model collection properties but foreach does not

    MVC Razor @foreach

相关问题