Given that select is not broken, what am doing wrong?
You are not respecting the convention for binding to a list
because you have holes in your indexes. You could use non-sequential indexes, like Guids. Look at Phil Haacks blog post I have linked to. He has an entire section dedicated to it.
Other possibility that I would recommend you is to use a view model. So go ahead and write one:
public class ItemViewModel
{
public string Id { get; set; }
public bool Selected { get; set; }
}
and then you could have a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new ItemViewModel { Id = "2" },
new ItemViewModel { Id = "8" },
new ItemViewModel { Id = "7" },
new ItemViewModel { Id = "6" },
new ItemViewModel { Id = "5" },
new ItemViewModel { Id = "4" },
new ItemViewModel { Id = "3" },
new ItemViewModel { Id = "1" },
};
return View(model);
}
[HttpPost]
public ActionResult Index(ItemViewModel[] model)
{
// everything will be correctly bound here
}
}
and a corresponding strongly typed view:
@model ItemViewModel[]
@using (Html.BeginForm())
{
for (var i = 0; i < Model.Length; i++)
{
Html.HiddenFor(x => x[i].Id)
Html.CheckBoxFor(x => x[i].Selected)
}
<button type="submit">OK</button>
}