views:

413

answers:

1

How do you create a databound checkbox list using linq-sql and asp.net mvc

thanks

A: 

Hey,

Simply setup a view like the following:

<% foreach (var item in Model) { %>
   <%= Html.CheckBox("check" + item.Key.ToString(), item.Selected) %>
<% } %>

Model contains an enumerable list of some LINQ object you have in your model. If there any other requirements?

Thanks.

Brian
how do i get the checked items on a form post?
raklos
Wrap them with <% Html.BeginForm(); %> and <% Html.EndForm(); %>. By default, the parameterless BeginForm does a post to the same action method as the one being requested, but there are overloads to accept the action and/or controller names.
Brian
Also note; checkboxes that are checked will have a value of True,False, because a hidden field is used to represent the false value, and has the same ID.
Brian
#Brian, but what if u need that product will be related to many categories (many-to-many), in this case u need to get ids and not true/false, so how can i do it?
msony
I've learned from another dev recently that if you give the checks the same ID, and store in the value of the check the category ID, when the post happens, an entry with that ID will have the items that were checked... Haven't tried that myself... In my original scenario though, to answer from that perspective, you loop through the checks with the appended ID to the ID of the element, and if it has a value of true in the value, then you know that category was selected. My answer was storing the ID of the category within the ID of the check element.
Brian