2

Trying to create a select list with a first option text set to an empty string. As a data source I have a List of a GenericKeyValue class with properties "Key" & "Value". My current code is as follows.

                <%= this.Select(x => x.State).Options(ViewData[Constants.StateCountry.STATES] as IList<GenericKeyValue>, "Value", "Key").Selected(Model.State) %>

This gets fills the select list with states, however I am unsure at this point of an elegant way to get a first option text of empty string.

aherrick
  • 19,799
  • 33
  • 112
  • 188
  • I was looking to accomplish this with the fluent approach MVC Contrib provides, I realize this can be done using the default MVC Drop Down List HTML Helper. – aherrick Jul 17 '09 at 12:47

4 Answers4

2

"Trying to create a select list with a first option text set to an empty string." The standard way isn't fluent but feels like less work:

ViewData[Constants.StateCountry.STATES] = SelectList(myList, "Key", "Value");

in the controller and in the view:

<%= Html.DropDownList(Constants.StateCountry.STATES, "")%>
keithm
  • 2,813
  • 3
  • 31
  • 38
1

Sure you can, but you add it to your list that you bind to the dropdown...

List<State> list = _coreSqlRep.GetStateCollection().OrderBy(x => x.StateName).ToList();
list.Insert(0, new State { Code = "Select", Id = 0 });
ViewData["States"] = new SelectList(list, "Id", "StateName", index);
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
James Fleming
  • 2,589
  • 2
  • 25
  • 41
0

Or this...

Your view;

<%=Html.DropDownList("selectedState", Model.States)%>

Your controller;

public class MyFormViewModel
{
    public SelectList States;
}

public ActionResult Index()
{
   MyFormViewModel fvm = new MyFormViewModel();
   fvm.States = new SelectList(Enumerations.EnumToList<Enumerations.AustralianStates>(), "Value", "Key", "vic");

   return(fvm);
}
griegs
  • 22,624
  • 33
  • 128
  • 205
0

Without extending anything - you can't.

Here's what author says:

One final point. The goal of MvcFluentHtml was to leave the opinions to you. We did this by allowing you to define your own behaviors. However, it is not without opinions regarding practices. For example the Select object does not have any “first option” functionality. That’s because in my opinion adding options to selects is not a view concern.

Edit:
On the other hand - there is 'FirstOption' method for Select in newest source code.
Download MvcContrib via svn, build and use.

Arnis Lapsa
  • 45,880
  • 29
  • 115
  • 195