模型的列表与LT的项目数目可变结合; T> [英] Model Binding with variable number of items in List<T>

查看:100
本文介绍了模型的列表与LT的项目数目可变结合; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可以在项目的变量数量模型的列表< T>

I have a model that can have a variable amount of items in a List<T>

在我看来,我则有以下几点:

In my view I then have the following:

@using (Html.BeginForm())
{
    int count = Model.Data.Filters.Count;
    for(int i = 0; i < count; i++)
    {
        <div>

        @Html.TextBox("filtervalue" + i)
        @Html.DropDownList("filteroptions"+i,Model.Data.Filters[i].FilterOptions)


        </div>
    }
    @Html.Hidden("LinkID", Url.RequestContext.RouteData.Values["id"])
}

有没有在我的控制器的方式,所以我可以设置绑定到变项的模型,它的POST操作方法?

Is there a way in my controller so I can set up the POST action method to bind to a model with variable items in it?

此外,我会怎么构建模型,以应对呢?

Also how would I construct the model to cope with this?

感谢

推荐答案

您coud使用编辑器的模板,它就会容易得多:

You coud use editor templates, it will be much easier:

@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Data.Filters)
    @Html.Hidden("LinkID", Url.RequestContext.RouteData.Values["id"])
}

和编辑模板内(〜/查看/共享/ EditorTemplates / FilterModel.cshtml )将被自动呈现的每个元素的 Model.Data.Filters 系列:

and inside the editor template (~/View/Shared/EditorTemplates/FilterModel.cshtml) which will be automatically rendered for each element of the Model.Data.Filters collection:

@model FilterModel
<div>
    @Html.TextBoxFor(x => x.FilterValue)
    @Html.DropDownListFor(x => x.SelectedFilterOption, Model.FilterOptions)
</div>

现在您的帖子控制器动作只会是这样的:

Now your POST controller action will simply look like this:

[HttpPost]
public ActionResult Foo(SomeViewModel model)
{
    // model.Data.Filters will be properly bound here
    ...
}

由于编辑模板,您再也不用编写任何foreach循环在你的意见或担心如何命名输入字段,发明一些索引,......使默认模型绑定承认他们在回发。

Thanks to editor templates you no longer have to write any foreach loops in your views or worry about how to name your input fields, invent some indexed, ... so that the default model binder recognizes them on postback.

这篇关于模型的列表与LT的项目数目可变结合; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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