I am developing an ASP.NET MVC 3 application in C# and I use Razor. I am now dealing with a problem concerning the binding of objects through ViewModels passed/received to/f
Don't write loops in a view. Use editor templates:
<strong>@Model.ContainerName</strong>
@using (Html.BeginForm())
{
<fieldset>
@Html.EditorFor(x => x.ItemData)
<input type="submit" value="Save" />
</fieldset>
}
and inside the corresponding editor template (~/Views/Shared/EditorTemplates/ItemPostModel.cshtml
):
@model ItemPostModel
@Html.TextBox(x => x.ItemId)
@Html.TextBox(x => x.ItemName)
@Html.TextBox(x => x.ItemValue)
And in the controller action you might need to specify the prefix:
[HttpPost]
public ActionResult UpdateItems(
int containerId,
[Bind(Prefix = "ItemData")]ItemPostModel itemData
)
{
//store itemData into repository
}
and that should be pretty much all. The editor template will take care of generating the proper input field names for the binding to work.