I have a list that I would like to group and edit within a razor view.
If the POCO is:
public class FooBar {
public string GroupName {get;set;}
public string SomeValue {get;set;}
// etc.
}
And the model in the View:
@model IEnumerable<FooBar>
And the Post action is like this:
[HttpPost]
public ActionResult FooBarPost(IEnumerable<FooBar> model)
Normally to edit a list I would use this syntax in my view:
@Html.EditorForModel()
Which works great, it creates lovely little inputs like:
<input id="[0].SomeValue" />
And the post back is perfect.
Now if I want to change my view to the much less awesome:
<fieldset>
<legend>Legendary</legend>
@foreach (var group in Model.GroupBy(x => x.GroupName))
{
<h3>@group.Key</h3>
@Html.EditorFor(x => group)
}
</fieldset>
Then when I post my list comes back as null?
I remember there being a trick to fixing this, I just can’t remember what it was?
Thanks.
Edit:
added [Bind(Prefix="group")] to my action which now brings back just one of the input values.
I noticed the HTML generated looks like this (all on same page):
Group 1:
<input id="group_0__SomeValue" name="group[0].SomeValues" type="hidden" value="bla">
<input id="group_1__SomeValue" name="group[1].SomeValues" type="hidden" value="bla">
Next group:
<input id="group_0__SomeValue" name="group[0].SomeValues" type="hidden" value="bla">
Assuming your goal is to render an editor for each unique instance of GroupName, change your code to look like the following:
On your controller side do something as this:
Sidenote
Don’t use foreach when trying to work with enumerables to render items in the view, otherwise they will not have an indexer in the name. @Html.EditorFor(x => groups[i]) and @Html.EditorFor(x => group) would render different name tag in HTML, so model binder wouldn’t recognize it as part of a collection that it should reconstruct as input for your action.