0

I'm using string[] roles = Roles.GetAllRoles() to get a string[] of all the ASP.NET membership roles for my application. I'm sending the roles to my view in ViewData and using a foreach to create a set of Checkboxes using <%: Html.CheckBox("RoleCheckBox") %>. There are 3 roles and my view does render 3 checkboxes. When I do a View/Source, I see the checkboxes and their corresponding hidden tags. They all have the same, so there are 6 tags with the name "RoleCheckBox" - 3 that render the checkboxes and 3 that are hidden.

The problem comes when I post the form back to my controller and bind the results - something like public ActionResult Create(Person person, string[] RoleCheckBox). I get FOUR strings and I have no idea where the fourth string ("false") is coming from. I could do some testing by trying various combinations of checks to see which one (hopefully) doesn't change and ignore it but that's just ugly.

Does anyone know why this would be happening?

Thanks,

Jay

1
  • I'm not clear what you're saying - you're generating three check boxes with the same HTML ID / form name? Isn't that just asking for trouble - can't you given them unique names? Or are you relying on ASP.NET to give them unique hierarchical names? The explanation for the hiddens: some old browsers used to simply omit off check boxes from the posted back data so you'd get no value returned at all for boxes that weren't ticked. The MVC helpers generate the hidden so that in those cases there will always be a value named RoleCheckBox returned. Commented Jun 11, 2010 at 13:02

1 Answer 1

0

The extra "false" comes because there are a pair (array) produced when the checkbox is checked, e.g. "true,false". The second false is coming from the hidden value. If it is not checked you get no first value because the checkbox returns nothing.

This link explains it in more detail and recommends to loop through the form keys and use "GetValues()" on each element and then get the first element in the resulting array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.