Kenny Kenny - 1 year ago 88
C# Question

Razor HTML dropdown list helper not selecting matching value

I have a view where I am creating a dropdown list. The list populates properly, but will not select the matching item for the page I'm editing.
On this page I am editing a Sermon record. The sermon model has the id of the series that it belongs to. I have confirmed that the series_id in the sermon record, and the matching one in the dropdown list are both "1". I did this by debugging model.sermon.Series_ID, and confirming that it was "1", and using Inspect in Chrome, I saw that there is a "1" on one of the items in the dropdown list.

Can anyone tell me why the dropdown list isn't selecting the matching series? There is no "selected" attribute being produced even though the number
that matches is present.


@model SermonLibraryManager.ViewModels.ViewModel

@Html.DropDownListFor(model => model.sermon.Series_ID, new SelectList(Model.seriesList, "Series_ID", "Series_Title"), "-- Select --")


namespace SermonLibraryManager.ViewModels
public class ViewModel
public SermonModel sermon;
public List<SermonModel> sermonList;
public SeriesModel series;
public List<SeriesModel> seriesList;


public class SermonModel
public int Sermon_ID { get; set; }
public string Series_Title { get; set; }
public int Series_ID { get; set; }
public string Sermon_Title { get; set; }
public DateTime Sermon_Date { get; set; }
public string Nickname { get; set; }
public string Last_Name { get; set; }
public string Topic { get; set; }
public string Description { get; set; }
public string UStream_ID { get; set; }
public string Vimeo_ID { get; set; }
public int? Main_Speaker { get; set; }


public class SeriesModel
public int Series_ID { get; set; }
public string Series_Title { get; set; }

Answer Source

For the Html.DropDownList helper method to select your value in the generated drop down you need to pass the value in the select list you're creating:

Look at the signature for the constructor of SelectList:

public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue)

You're just passing the values, but you're not specifying the selectedValue. It could be a model property, for instance.

Let's say you have a property called SerieID inside your viewmodel. So, the following will effectively select the item in the drop down matching the value of your property:

@Html.DropDownListFor(model => model.sermon.Series_ID, new SelectList(Model.seriesList, "Series_ID", "Series_Title", Model.SerieID), "-- Select --")

Hoe this helps!