Oct 1 2009

ASP.Net MVC 1.0 and Html.CheckBox

Category: amilsark @ 18:40

With a background in ASP.Net web forms, the Html.CheckBox used with ASP.Net MVC did not behave how I thought it would.

For example when adding a checkbox to the View inside a table:

   1: <%=Html.CheckBox("cb" + item.player.idPlayer)%>

Firebug shows me this rendered in the html source of the page:

image


What is that hidden field for???


A developer on the Microsoft ASP.Net team said that this was by design so that we can properly assign a value of ‘false’ to an unchecked checkbox (link). 

I’m assuming this was the fix for the issue in the MVC 1.0 RC builds where a null value was being returning for unchecked checkboxes.


But in ASP.Net MVC 1.0, here is what the Request.Form values are (notice all checkbox inputs are listed with either a value of ‘false’ or ‘true’):

image

 


So in my case to loop through the returned inputs and grab the Player ID’s which have been checked:

Here is the controller action code to look for checked checkboxes (from Andrey Tkach on Stack Overflow):




   1: var selectedPlayerIds = new List<int>();
   2:             IEnumerable<Player> players;
   3:  
   4:             foreach (string key in Request.Form)
   5:             {
   6:                 var checkBox = String.Empty;
   7:                 if(key.StartsWith("cb"))
   8:                 {
   9:                     checkBox = Request.Form["" + key];
  10:                     if (checkBox != "false")
  11:                     {
  12:                         int id = Convert.ToInt32(key.Remove(0, 2));
  13:                         selectedPlayerIds.Add(id);
  14:                     }
  15:                 }
  16:             }





I am now able to use these playerID’s for interaction with the repository and perform interesting logic.

Tags: , ,