Table of contents
Generating selects
FormHelper is able to generate single and multi-value selects. Make sure you have read the How FormHelper works with sets document.
Single value selects
To create a select just specify the target and the data source which would be a set of all elements so it can create options for.
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["oneprime"] = 3; }
The code on the view to use it would be:
$FormHelper.Select("oneprime", $primenumbers)
Complex objects
With complex objects you must care to specify the value and text parameters so the FormHelper can generate proper html elements.
Consider the following action code:
public void Index() { // data source IList authors = new Author[] { new Author(1, "hammett"), new Author(2, "john doe"), new Author(3, "someone else") }; PropertyBag["authors"] = authors; // initial selection Blog blog = new Blog(); blog.Author = new Author(1, "hammett"); PropertyBag["blog"] = blog; }
The Author class above has an Id property and Name property. So here is how the view would use it:
$FormHelper.Select("blog.author.id", $authors, "%{value='id', text='Name', firstoption='Please select'}")
Note the use of firstoption parameter. It includes the specified content as the first available option on the select.
Multi-value selects
Multi-value selects are not very different from what we have seen so far. The initial selection however will be a set.
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["multipleprimes"] = new int[] { 3, 5, 7 }; }
Here is how the view would use it:
$FormHelper.Select("multipleprimes", $primenumbers, "%{multiple='true', style='width: 110px; height: 90px;'}")
Note that the multiple parameter is required to generate a html element prepared for multiple selection.