Table of contents
CheckboxList
FormHelper allows you to generate a list of checkboxes associated with a data source. It is also able to pre-check the checkboxes based on the initial selection set. Make sure you have read the How FormHelper works with sets document.
Simple example
Listing checkboxes requires a state object. To create it you invoke CreateCheckboxList which returns a CheckboxList instance. A CheckboxList is enumerable and exposes an Item method. You must enumerate the elements and while doing it invoke Item which returns the checkbox element.
Consider the following action code:
public void Index() { // data source PropertyBag["primenumbers"] = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 }; // initial selection PropertyBag["selectedPrimes"] = new int[] { 11, 19, 29 }; }
The code on the view to use it would be:
<p> #set($items = $FormHelper.CreateCheckboxList("selectedPrimes", $primenumbers)) #foreach($elem in $items) $items.Item() $elem <br/> #end </p>
Complex objects
With complex objects you must care to specify the value parameter so the FormHelper can generate proper html elements.
Consider the following action code:
public void Index() { // data source Category[] categories = new Category[] { new Category(1, "Music"), new Category(2, "Humor"), new Category(3, "Politics") }; PropertyBag["categories"] = categories; // initial selection Blog blog = new Blog(); blog.Categories = new Category[] { new Category(2, "Humor") }; PropertyBag["blog"] = blog; }
The Category class above has an Id property and Name property. So here is how the view would use it:
<p> #set($items = $FormHelper.CreateCheckboxList("blog.categories", $categories, "%{value='Id'}")) #foreach($elem in $items) $items.Item() $elem.Name <br/> #end </p>