locked
SelectLists and null values RRS feed

  • Question

  • User-1328661193 posted

    Most times I don't want a preselected item.

    It's too bad that

    SelectList(System.Collections.IEnumerable items, string dataValueField, string dataTextField, object selectedValue)

    doesn't take a null for selectedValue and automatically appends a <option value="" /> to the <select>.

    Wednesday, June 25, 2008 11:55 AM

All replies

  • User-1660457439 posted

    This works perfectly fine on my machine:

                object[] somearray = new object[] {
                    new { Foo = "Foo1", Bar = "Bar1" },
                    new { Foo = "Foo2", Bar = "Bar2" }
                };
                SelectList somelist = new SelectList(somearray, "Foo", "Bar", null);
                ViewData["somelist"] = somelist;

    Then in the view:

    <%= Html.DropDownList("somelist") %>

    This produces:

    <select name="somelist" id="somelist">
    <option value="Foo1">Bar1</option>
    <option value="Foo2">Bar2</option>
    </select>

    (By the way, yes, you really do want a default selected item according to the W3C.  We're considering automatically preselecting the first item if no item in the dropdownlist is selected.)

    Wednesday, June 25, 2008 12:50 PM
  • User-1772813213 posted

    There should be someway to specify if the list value is being saved to a nullable type and if so a blank option should be placed at the start of the list.

    For example, say I have an object:

    public class Person {
    public int AddressCountryID { get; set; }
    public int? BirthCountryID { get; set; }
    }

    I don't want to have to have 2 different Country lists on my viewdata just to add a null value to one of them.

    We don't want to encourage people having "Please select an option..."; that is not right, but the situation above is a common and viable one.

    Wednesday, August 6, 2008 10:32 AM