问题
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