Reputation: 683
Working with MVC I have a FormModel:
public class FormModel
{
public string Description { get; set; }
public List<CustomList> CustomList { get; set; }
public FormModel(){}
}
The FormModel class consists of a list of the class CustomList:
public class CustomList
{
public int CustomListId { get; set; }
public string Description { get; set; }
public List<String> StringList{ get; set; }
public CustomerList(){}
}
which contains a list of Strings. What I want to achieve is setting up a form that allows the user to edit each of the values in StringList. To do so I set up my view:
@model CMS.Models.FormModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using(Html.BeginForm("DoStuff", "Create", Model))
{
<div>
<p>Description: @(Html.EditorFor(e => e.Description))</p>
@for (int i = 0; i < Model.CustomList.Count; i++)
{
@Html.LabelFor(l => l.CustomList[i].Description)
@Html.HiddenFor(h => h.CustomList[i].CustomListId)
for (int a = 0; a < Model.CustomList[i].StringList.Count; a++)
{
@Html.EditorFor(e => e.CustomList[i].StringList[a])
}
}
<input type="submit" />
<div>
}
On submit the Description in FormModel is returned to the controller but CustomList is returned back Empty. I've checked a few of links from Joe Stevens but seems i'm missing something. Any help would be appreciated.
Upvotes: 1
Views: 2044
Reputation: 2674
Instead of:
@using(Html.BeginForm("DoStuff", "Create", Model))
Try:
@using(Html.BeginForm("DoStuff", "Create", FormMethod.Post))
Hope this works for you!
@Mystere Man I don't think that instantiating the lists in the constructor was the issue. I have never heard of or experienced that being an issue with model binding, although that is always a good practice with lists anyway.
Upvotes: 1
Reputation: 93424
You need to instantiate an empty list in the constructor of both your models. The default model binder does not create the empty Lists for you. Since there is no list object, it won't bind the values.
It looks correct otherwise.
Upvotes: 0