SaltProgrammer
SaltProgrammer

Reputation: 1055

ModelBinder Not Correctly Binding to List On Submit

I'm trying to set up the HTML for the checkboxes correctly so they can bind to a list property, but can't seem to do so successfully. In the view code below I have five checkboxes. It only binds when I check at least the first checkbox. If I check all four checkboxes except the first one, nothing gets bound.

This is the code that I have:

  public class People
  {
    public List<Person> Crew { get; set; }
    public string TeamName { get; set; }

    public List<string> StatesLiveIn { get; set; }

  }

  public class Person
  {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
  }

View:

@model TestBinder.Models.People

@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm()) 
{ 

  @Html.TextBoxFor(m => m.TeamName);  


  <h2>Crew #0</h2>
  <h3>FirstName:</h3>                                  
  @Html.TextBoxFor(m => m.Crew[0].FirstName); <br />

  <h3>LastName: </h3>
  @Html.TextBoxFor(m => m.Crew[0].LastName);<br />

  <h3>Age: </h3>
  @Html.TextBoxFor(m => m.Crew[0].Age);<br />


  <h3>States Lived In: </h3>
  int i = 0;
  foreach (string state in new List<string>() { "NY","NJ","FL","IL","TX" })
  {     
    @state <input checked="checked" type="checkbox" value="@state" name="StatesLiveIn[@i]" /><br />  
    i++;
  }                                             

  <input type="submit" value="submit" />
}

Controller:

public ActionResult Index()
{   
  return View();
}

[HttpPost]
public ActionResult Index(People p)
{    
  return View(p);
}

Thanks.

Upvotes: 1

Views: 169

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

Try giving your checkboxes the same name:

<h3>States Lived In: </h3>
foreach (var state in new[] { "NY", "NJ", "FL", "IL", "TX" })
{     
    @state 
    <input checked="checked" type="checkbox" value="@state" name="StatesLiveIn" />
    <br />  
}

But a better alternative is to use a view model, editor templates and the strongly typed CheckBoxFor helper because you have hardcoded the checked="checked" attribute and if there are validation errors and you render the same view in the POST action the user will lose its selections.

Upvotes: 2

Related Questions