views:

5998

answers:

6

Why is the CheckBoxList removed from asp.net MVC preview release 5? Currently i don't see any way in which i can create a list of checkboxes (with similar names but different id's) so people can select 0-1-more options from the list.

There is an CheckBoxList list present in the MVCContrib library but it is deprecated. I can understand this for the the other HtmlHelpers but there does not seem to be a replacement for the CheckBoxList in preview 5.

I would like to create a very simple list like you see below, but what is the best way to do this using asp.net MVC preview release 5?

<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="goed"> goed
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="redelijk"> redelijk
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="matig"> matig
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="slecht"> slecht
+14  A: 

A for loop in the view to generate the checkboxes

<% foreach(Inhoud i in ViewData["InhoudList"] as List<Inhoud>) { %>
  <input type="checkbox" name="Inhoud" value="<%= i.name %>" checked="checked" /> <%= i.name %>
<% } %>   

Don't use Html.Checkbox, as that will generate two values for each item in the list (as it uses a hidden input for false values)

Corin
I am getting error while this as can not convert ViewData to generic lists (List)...why should this?
Lalit
+6  A: 

I recently blogged about implementing the CheckBoxList helper in the MVC Beta. Here is the link.

JeremiahClark
A: 

I recommend using JeremiahClark extension posted above. (CheckBoxList)

My controller resulted into very simple instructions. For clarify I add a fragment of my code that's absent in the sample.

        var rolesList = new List<CheckBoxListInfo>();
        foreach (var role in Roles.GetAllRoles())
        {
            rolesList.Add(new CheckBoxListInfo(role, role, Roles.IsUserInRole(user.UserName, role)));
        }
        ViewData["roles"] = listaRoles;

And in the view:

<div><%= Html.CheckBoxList("roles", ViewData["roles"]) %></div>

That's all.

jrojo
+1  A: 

I have my own implementation of CheckListBox which has support for ModelState. If your are interested it's here. The post is in spanish, but you shouldn't have problem reading the code.

What is interesting in Jeremiah solution is the fact that you can set the initial state of the checkboxes, something you can't do with my CheckListBox.

Gerardo Contijoch
A: 

Why using "CheckBoxListInfo" when ASP.NET MVC comes with SelectListItem ?

Mauro
A: 

For the cleanest, hassle free solution, this works well: http://stackoverflow.com/questions/3291501/asp-net-mvc-maintain-state-of-a-dynamic-list-of-checkboxes/3298821#3298821

I agree with the first answer too, I wouldn't touch Html.CheckBox, it creates more problems than it solves.

Aaron