Model binding things other than textboxes could be tricky in ASP.NET MVC. To correctly model bind, one has to follow a specific naming/value conventions in the HTML.
Let’s say we have a model object called People, and we have a List
public class People { public List<string> StatesLiveIn { get; set; } } |
And in our View we have as follows:
@model TestBinder.Models.People foreach (string state in new List<string>() { "NY","NJ","FL","IL","TX" }) { @state <input type="checkbox" value="@state" name="StatesLiveIn" /><br /> } |
Out controller simple looks like this:
public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(People p) { return View(p); } |
If we put a trace point at the return line, and inspect after the user has submitted only NY and TX…
…we’ll see that it was correctly bound…