I’m working on a page where the user needs to fill in some information and finally make a selection of 1 or more customers with check-boxes.
The list of customers is an IEnumerable<Customer> which I pass into my Model. How would I go about creating the list of check-boxes using .CheckBoxFor()?
And finally I would like to be able to validate if at least 1 check-box has been selected.
Request is the object which holds the information the user entered.
<% foreach (var customer in Model.Request.Customers) { %>
<%= Html.CheckBoxFor(/* customer */) %>
<% } %>
Can anyone point me in the right direction? Or am I going about this all wrong?
You could create a custom html extensions class and overload the CheckBoxFor method like below. The method evaluates the metadata.Model to the value passed into it (like U.S. State). You can get the checkbox value/s from the FormCollection in the ControllerAction:
Example assumes a keyvaluepair generic list
HtmlExtensions.cs
While I’m at it, here’s my list of United States to complete code: