开发者

ASP.NET MVC 2 - Checkboxes

开发者 https://www.devze.com 2023-01-02 23:01 出处:网络
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 s

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") %&g开发者_开发百科t;. 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消