title: ASP.NET MVC: Model binding half an object
body: <p>I have a form to add a new user with a few checkboxes for user roles. I have a model in my action called User which has the following properties:</p>
  
  <pre><code>public string Username { get; set; }
  public string Password { get; set; }
  public IEnumerable&lt;UserRole&gt; Roles { get; set; }
  </code></pre>
  
  <p>Inside the UserRole class I have two properties:</p>
  
  <pre><code>public int Id { get; set; }
  public string Name { get; set; }
  </code></pre>
  
  <p>In my form I can successfully bind to Username and Password no problem by giving the input names 'Username' and 'Password'. When the page initially loads the user role details are loaded and so all I need to pass back in is the Id because this is what the service needs to associate a user with a user role.</p>
  
  <p>I thought I could do this the simple way by giving each checkbox the value of the role Id and passing that in to Roles therefore partially completing the roles class and leaving the Name field of the role object blank. An example checkbox looks like this:</p>
  
  <pre><code>&lt;input type="checkbox" id="addUserAdministrator" name="Roles.Id" value="@Model.Roles.Where(role =&gt; role.Name == "Administrator").Select(role =&gt; role.Id).First()" class="css-checkbox"/&gt;
  </code></pre>
  
  <p>However this never populates the Roles collection and it is always null. Is there a way of doing this or will I need to do the long winded way of passing in a list on ints and creating the model in the action?</p>
  
  <p>EDIT:</p>
  
  <p>My action looks like this:</p>
  
  <pre><code>public RedirectToRouteResult Add(User user)
  </code></pre>