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
You coud use editor templates, it will be much easier:
and inside the editor template (
~/View/Shared/EditorTemplates/FilterModel.cshtml) which will be automatically rendered for each element of theModel.Data.Filterscollection:Now your POST controller action will simply look like this:
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.