Model Binding with variable number of items in List<T>

做~自己de王妃 提交于 2019-12-11 17:10:07

问题


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"])
}

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?

Thanks


回答1:


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"])
}

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

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.



来源:https://stackoverflow.com/questions/7431702/model-binding-with-variable-number-of-items-in-listt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!