Note that there are some explanatory texts on larger screens.

plurals
  1. POPopulate child view model collection when posting to controller
    primarykey
    data
    text
    <p>I have a page where you can add a Company. A company has multiple Employees. Here are my view models:</p> <pre><code>public class CompanyViewModel { [ScaffoldColumn(false)] public int CompanyId { get; set; } public string Name{ get; set; } public List&lt;EmployeeViewModel&gt; Employees { get; set; } } public class EmployeeViewModel { [ScaffoldColumn(false)] public int EmployeeId { get; set; } public int CompanyId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } </code></pre> <p>On my page, I have jQuery functionality to add/delete Employees dynamically. When I post my form, my view looks like this:</p> <pre><code>&lt;input id="CompanyId" name="CompanyId" type="hidden" value="0" /&gt; &lt;input id="Name" name="Name" type="text" value="Test company name" /&gt; &lt;input id="Employees[1].FirstName" name="Employees[1].FirstName" type="text" value="fn1" /&gt; &lt;input id="Employees[1].LastName" name="Employees[1].LastName" type="text" value="ln1" /&gt; &lt;input id="Employees[2].FirstName" name="Employees[2].FirstName" type="text" value="fn2" /&gt; &lt;input id="Employees[2].LastName" name="Employees[2].LastName" type="text" value="ln2" /&gt; &lt;input id="Employees[3].FirstName" name="Employees[3].FirstName" type="text" value="fn3" /&gt; &lt;input id="Employees[3].LastName" name="Employees[3].LastName" type="text" value="ln3" /&gt; </code></pre> <p>And my controller method:</p> <pre><code>[HttpPost] public ActionResult Create(CompanyViewModel viewModel) { ... } </code></pre> <p>When I go through the debugger to see what's in my view model after I post the form, the Employees collection is null. CompanyId and Name are passed through, but not the Employees collection.</p> <p>I've also tried changing the id and name of the input from <code>Employees[1].FirstName</code> to <code>Model.Employees[1].FirstName</code>, but that didn't help either.</p> <p>What am I doing wrong here?</p> <p>I'm using MVC 3 and Razor.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload