Setting Selected Item in FluentHtml Select List

I ran into a small issue today when using the FluentHtml Select() HtmlHelper.  My original code was not properly setting the value of the selected item in the drop down:

<%=this.Select(m => m.Motorcycle.Make).Selected(Model.Motorcycle.Make).Label("Vehicle Make").Options(Model.MakeList)%>

I kept ending up with no item being selected from the drop down even though I definitely had a vehicle Make populated in my model and my drop down was correctly populated with the collection from the “MakeList” property of the view model.  It turns out that the solution was a simple matter of corrected ordering:

<%=this.Select(m => m.Motorcycle.Make).Options(Model.MakeList).Selected(Model.Motorcycle.Make).Label("Vehicle Make")%>

In hindsight I guess this order makes a little more sense intuitively anyway.  However, the fluent API did not constrain me from running into this issue.  So, just a heads up, when using the Select() helper, set the Options() first, and then set the selected value by invoking the Selected() helper method.

posted on Thursday, October 22, 2009 2:30 PM Print
# re: Setting Selected Item in FluentHtml Select List
Tim Scott
10/23/2009 12:22 AM
It definitely should not not matter in what order you chain Options and Selected methods. I tried but could not replicate. See here:

Notice test 'basic_select_renders_with_options_from_dictionary.' I tried to replicate using over overloads of Options, and could not, but that shoulld not matter anyway. The options HTML is never rendered until ToString is called, which is always after all chained methods are called.

Maybe I'm missing something. If could tell me how to replicate, I would love to correct it.
# re: Setting Selected Item in FluentHtml Select List
10/23/2009 10:57 AM
@Tim - I'll send you an email with a zip file. Thanks!
# re: Setting Selected Item in FluentHtml Select List
Tim Scott
10/23/2009 11:59 AM
I did not even have to open your zip to see why this is. It's IEnumerable's deferred execution. I should be able to fix fairly readily. Look for it soon.
# re: Setting Selected Item in FluentHtml Select List
Tim Scott
10/24/2009 1:19 PM
Hmm, I cannot replicate. Look at the SelectTests methods:


All pass and call Selected first. I'm stumped as to what accounts for the difference. If you feel ambitious maybe you could write a failing test. :)

Post Comment

Title *
Name *
Comment *  

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers

Google My Blog

Tag Cloud