views:

776

answers:

4

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.

+2  A: 

"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, "")%>
Keith Morgan
A: 

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
A: 

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 L.
+1  A: 

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

List 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);

enjoy!

James Fleming
I have actually gone down this route thanks...
aherrick