I've been wrestling with this for hours and I can't seem to apply any kind of logic that will work.I have a collection of objects, lets call them items, that have a boolean property to define if they are to be included later when adding to a basket. The problem I'm having is that I want a page that lists these items and has a checkbox next to each one, which toggles whether the item is to be included or not.
I have this:
@using(Ajax.BeginForm("UpdateItems", "Controller", null,
new AjaxOptions { HttpMethod = "Post"}, new { id = "UpdateItemsForm" })
{
@foreach(var item in collection)
{
@Html.CheckBox("itemIncluded", item.Included)
}
}
<script>
$("#UpdateItemsForm").change(function ()
{
$(this).submit();
});
</script>
In Controller I have
public JsonResult UpdateItems(bool[] itemIncluded)
{
//Do Something unimportant
}
The problem is that in my controller I am getting an array of bools, which I want, but the length of the array is inconsistent, when I change a checkbox I will receive an array of n elements, depending on how many boxes are checked, e.g if I check 2/4 boxes I'll get an array of 6 bools. This array will contain a true and a false element for the box checked. Is there any way I could enforce an array size, i.e. Always get an array with a single element for each checkbox, with true or false if it is checked or not?
@Html.CheckBoxFor? If you'd post that you would get whether it's selected as well.@Html.DisplayFor(collection)and then just build a custom display.@Html.CheckBoxForI get null, not an array, in the controller.