2

I have this code:

Model:

public bool[] ArrayOfBooleans = new bool[2];

View

@using(Html.BeginForm())
{
    @:#1
    <input name="ArrayOfBooleans[0]" type="checkbox" value="true" />
    <input name="ArrayOfBooleans[0]" type="checkbox" value="false" />
    <br />
    @:#2
    <input name="ArrayOfBooleans[1]" type="checkbox" value="true" />
    <input name="ArrayOfBooleans[1]" type="checkbox" value="false" />
    <br />    
    <input type="submit" value="Submit"/>
}

When I post this I don't get any changes in ArrayOfBooleans. Is it even possible to "attach" check box to an array element?

NOTE: This is simplified form of a real problem of mine. I have to use collections and more complex objects.

Miro
  • 1,778
  • 6
  • 24
  • 42

1 Answers1

3

Try this(works for me):

@using(Html.BeginForm())
{
    @:#1
    <input name="ArrayOfBooleans[0]" type="checkbox" value="true" />
    <input name="ArrayOfBooleans[0]" type="hidden" value="false" />
    <br />
    @:#2
    <input name="ArrayOfBooleans[1]" type="checkbox" value="true" />
    <input name="ArrayOfBooleans[1]" type="hidden" value="false" />
    <br />    
    <input type="submit" value="Submit"/>
}

And in model:

public class A
{
    public bool[] ArrayOfBooleans { get; set; }
}

In Controller:

[HttpPost]
public ActionResult Index(A model)
{
    return View();
}
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • 1
    This is ugly to have to add the second input of the same name to get the false boolean values from the checkbox, but it works. Hidden input **must be after** the corresponding checkbox input. The first value assigned to a name sticks and won't be overwritten. If the checkbox is not checked, it doesn't write 'true' to the named value so that leaves the named value open for the hidden input to write false to it. +1 from me. – Kent Nov 29 '12 at 01:01