I’m using EF with MVC3.
I have a model with a custom list:
public List<MarketingModel> Marketing { get; set; }
I initialise this in the constructor as:
this.Marketing = new List<MarketingModel>();
I view it in the View:
@foreach (MarketingModel m in Model.Marketing)
{
<td class="title">@Html.DisplayFor(model => m.Name)</td>
<td>@Html.CheckBoxFor(model => m.Mail)</td>
<td>@Html.CheckBoxFor(model => m.Email)</td>
}
Which populates fine. However when saving the page, it for whatever reason passes Marketing as a null value.
Really stumped on this.
Don’t use a
foreachloop. theXXXForhelper methods use expression trees designed to determine the property path to your property from the model. This property path is used to construct thenameattribute on the corresponding HTML input elements.Since you are not consuming the model in your lambda (
model => m.Name<– note that you are not usingmodel) the property path is incorrect. Instead, use aforloop:This way, the entire path to the property is contained in your expression tree (
Model.Marketing[i].Name) and the correspondingnameattribute should contain that full path now. Thus upon saving, the data should now be there.