I'm still experimenting but this seems to get along with the default binder and persists the user selections after post.. Hidden fields, really?? .. will this fly in html5 ? This feels crazy but I'd rather do this than hit my db for drop down lists and checkbox lists just because ModelState.IsValid is false..
public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, List<SelectListItem> list, string ModelCollectionName)
{
var sb = new StringBuilder();
if (list != null)
{
int i = 0;
foreach (var l in list)
{
string collectionNameIndex = String.Format("{0}[{1}]", ModelCollectionName, i);
var hiddenName = new TagBuilder("input");
hiddenName.Attributes.Add(new KeyValuePair<string, string>("type", "hidden"));
hiddenName.Attributes.Add(new KeyValuePair<string, string>("name", String.Format("{0}.{1}", collectionNameIndex, "Text")));
hiddenName.Attributes.Add(new KeyValuePair<string, string>("value", l.Text));
var hiddenValue = new TagBuilder("input");
hiddenValue.Attributes.Add(new KeyValuePair<string, string>("type", "hidden"));
hiddenValue.Attributes.Add(new KeyValuePair<string, string>("name", String.Format("{0}.{1}", collectionNameIndex, "Value")));
hiddenValue.Attributes.Add(new KeyValuePair<string, string>("value", l.Value));
var checkBoxTag = htmlHelper.CheckBox(String.Format("{0}.{1}", collectionNameIndex, "Selected"), l.Selected);
var labelTag = new TagBuilder("label");
labelTag.Attributes.Add(new KeyValuePair<string, string>("for", String.Format("{0}.{1}", collectionNameIndex, "Name")));
labelTag.SetInnerText(l.Text);
sb.Append(hiddenName);
sb.Append(hiddenValue);
sb.Append(checkBoxTag);
sb.Append(labelTag);
sb.Append("<br/>");
i++;
}
}
return MvcHtmlString.Create(sb.ToString());
}