IEnumerable property is null after submit

asp.net-mvc, asp.net-mvc-4, c#, entity-framework, razor

Solution

That's because in order to correctly index your fields (so model binder can do it's work), you have to use a `for` loop.

First, change your `IEnumerable` to be a `List` (so we can use an indexor in the view).

Then change your `foreach` to be the following `for` loop:

@for (int i = 0; i < Model.EmailAddressList.Count; i++)
{
    <div id="@Model.EmailAddressList[i].AddressType">
        <p>
            @Html.TextBoxFor(m => m.EmailAddressList[i].EmailAddress, new { @class = "input-xxlarge" })
        </p>
    </div>
}

Problem

I am new to MVC and have some difficulties understanding this. To make it simple, I have a "Person" object and this object has an IEnumerable property called "EmailaddressList". I have generated an edit page through Visual Studio 2012. The main objects properties, are generated on the edit page with textboxes like Name and LastName. However the list of e-mail addresses in the IEnumerable list of sub-objects are not generated automatically in my view. This is OK, I have written that code by hand using a tab for each type of e-mailaddress. So far so good. Problem: When I recieve the model (person object) in my HTTP-Post method, the EmailAddressList is null. Why is it like this, It was not null when I sent it to the view. I the tab where the e-mailadresses are listed is in a partial view. Can anyone give me some tips, is it something I'm missing here?* View-Code ``` <div id="tabs"> <ul> @foreach (var item in Model.EmailAddressList) { <li><a href="#@item.AddressType">@Html.Label(item.AddressType)</a></li> } </ul> @foreach (var item in Model.EmailAddressList) { <div id="@item.AddressType"> <p> @Html.TextBoxFor(s => item.EmailAddress, new { @class = "input-xxlarge" }) </p> </div> } </div> ``` Controller (recieving method) Here person.EmailAddressList is null ``` [HttpPost] public ActionResult Create(Person person) { if (ModelState.IsValid) { personRepository.InsertOrUpdate(person); personRepository.Save(); return RedirectToAction("Index"); } else { return View(); } } ```

Original source

Related problems