My Software Notes

Useful things I discover

ASP.NET MVC SelectList Constructor

with 12 comments

I was creating a drop down list in an MVC application and the list was okay, but the selected item was not being selected.

I was using the SelectList object and the constructor that takes four parameters, the last parameter being selectedValue.  The documentation on MSDN is not exactly enlightening.  All it says for the parameter is “The selected value”.  Wow, big help.

This is what I finally figured out.

Here is the constructor:

public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField,
    Object selectedValue
)
  • items is the list of “things” you want to put in the drop down list (“select” HTML tag).
  • dataValueField is the name of the property on your “things” that you want to be put into the “value” attribute of the “option” tag rendered in the HTML.
  • dataTextField is the name of the property on your “things” that you want to be displayed in the drop down list (the text between the “<option>” and “</option>” in the “select”) .
  • selectedValue is the value you want to end up as selected in the drop down list. It has to be the same as what will be put into the “value” attribute of the “option” tag in the rendered HTML.

Example:  I have a class called Thing that has a property “ID” and a property “Description”.  I want something like this:

<select>
<option value="1">Description One</option>
<option value="2" selected="selected">Description Two</option>
<option value="3">Description Three</option
</select>

I have a List<Thing> that I will use to populate the drop down. I have a Thing that is the selected Thing.

List<Thing> things = GetThings();
Thing selectedThing = GetSelectedThing();
var selectList = new SelectList(things, "ID", "Description", selectedThing.ID);
ViewData["things"] = selectList;

So it works if the fourth constructor parameter is the exact value you want to match.  I’m not sure if it needs to be a string or not, I’ve not had time to check that.

03/11/2013 – I just came across these two excellent articles on using the Html.DropDownList and Html.DropDownListFor helper methods.  These might also shed some light on how to work with SelectList and why you may not even need to:

Drop-down Lists and ASP.NET MVC

DropDownListFor with ASP.NET MVC

 

Written by gsdwriter

February 17, 2010 at 4:56 pm

Posted in ASP.NET MVC

12 Responses

Subscribe to comments with RSS.

  1. I had the exact same trouble and came to the same conclusion you did. I REALLY wish the documentation for this stuff on MSDN was far less crappy.

    Troy Campbell

    June 20, 2010 at 1:14 am

  2. Fantastic, I stumbled across this after I’d given up trying to do it and was googling something else! Excellent ta very much 🙂

    Dan G

    February 16, 2011 at 1:41 pm

    • You’re welcome!

      gsdwriter

      February 17, 2011 at 8:18 am

  3. Thanks for this – solved an hour of pain for me.
    You’d think the Microsoft documentation would scream this from the rafters?

    scott

    December 15, 2011 at 3:23 pm

    • I’ve noticed that the documentation for the MS open-source projects is generally very poor. The Web API is another example of a great looking project with lousy documentation. It starts well, with a good intro, but the details of the classes, etc. are almost impossible to find. I guess you could delve into the code itself but I just don’t have time for that when I’m trying to get something done.

      gsdwriter

      December 21, 2011 at 9:17 am

  4. Does this work for the Html.DropDownListFor helper? What would it look like? I can populate my dropdownlist but it’s not passing the selected value to the post.

    Loren Nicole

    February 11, 2012 at 3:00 pm

    • @Loren Nicole

      I’d say, try it and see. The constructor of the SelectList was what solved it for me, because that was where the selected value was being set. Once it was set in the SelectList, the Html helper rendered the selected value correctly.

      If that doesn’t work then another way to do it is to create the SelectListItem objects yourself, setting Selected = true on the single object that you want to be the selected one. Then add them to the SelectList using the Items property – ugly, but it should work if nothing else does.

      gsdwriter

      February 13, 2012 at 8:53 am

  5. Nice post 🙂

    If using EF, i like to use the LINQ Where method to build the “thing” as this allows me to build some nice selection logic within the SelectList instantiation.

    Example, if i have a RecordStatus field to handle logically deleted records (status=”X”), and i dont want these records in my selectlist:

    var currencyTypes = new SelectList(db.CurrencyTypes.Where(c => c.RecordStatus != “X”), “id”, “Description”);
    var transactionTypes = new SelectList(db.TransactionTypes.Where(t => t.RecordStatus != “X”), “id”, “Description”);

    garfbradaz

    May 23, 2012 at 2:17 pm

    • @garfbradaz – LINQ is pretty awesome!

      gsdwriter

      June 3, 2012 at 8:18 am

  6. I did exactly as you suggested but my code still not working. Anything that you can suggest

    //enum
    public enum Gender
    {
    UNKNOWN = 0,
    MALE = 1,
    FEMALE = 2
    }

    //action method
    public ActionResult Edit(int id=0)
    {
    Employee employee = context.Employees.Find(id);
    if (employee == null)
    {
    return HttpNotFound();
    }

    var genders = (from Gender g in Enum.GetValues(typeof(Gender))
    select new SelectListItem
    {
    Value = ((int)g).ToString(),
    Text = g.ToString(),
    Selected = ((int)g == (int)employee.Gender)
    }).ToList();

    var selectedItem = genders.FirstOrDefault(g => g.Selected == true);

    var genderSelectList = new SelectList(genders, “Value”, “Text”, selectedItem.Value);

    ViewBag.Gender = genderSelectList;
    return View(employee);
    }

    //razor
    @Html.DropDownListFor(model => model.Gender, (SelectList)ViewBag.Gender)

  7. My mistake – I should have used DropDownList instead of DropDownListFor.
    I assume the DropDownListFor should only be used in case of ViewModel and not otherwise.

    • Glad you sorted it out. I hope my article helped.

      gsdwriter

      March 16, 2014 at 10:16 am


Leave a reply to Troy Campbell Cancel reply