Was banging my head trying to figure out how to set the default value for a drop down list in a view that I was creating. I created the view using a view-specific model that was crafted to contain the data model plus the list of values needed for the dropdown list.
I thought I was being smart and used the SelectList object to pass in the selections for my dropdown. It stated that it had a constructor parameter that would set the default value. My code in my controller looked somthing like this:
search.Locations = new SelectList(db.Locations, "LocationCode", "LocationName", "HERE");
According to the documentation for SelectList, you can pass in a list of values. In this case, I used a database table which I had created using Entity Framework which contained a list of locations. The next two parameters told the class which fields to use as the value and text for the select items. The last parameter is supposed to be a default value which would be selected.
In my view, I had created a dropdownlist control thus:
@Html.DropDownListFor(model => model.Location, Model.Locations)
My table was seeded with locations and indeed did have a value of “HERE” in LocationCode in one of the records. Imagine my surprise when I ran the project and went to the view to find that it did not properly select the default value in the dropdown. A quick look at the source for the page confirmed that the html did not reflect that the option which had the value of “HERE” was to be the selected one.
Needless to say, I did some reading and finally found out that it is a known behavior. I won’t say bug, because there seems to be some disagreement whether the behavior was intentional, or not. However there was a fix.
I changed my code in the controller to do the following:
search.Location = "HERE"; search.Locations = new SelectList(db.Locations, "LocationCode", "LocationName", string.Empty);
The obvious change is that I seeded the field in my model with the default value and passed an empty string to the constructor for the SelectList. Obviously, it was ignoring it anyway, so good riddance.
Now, when I run the project, the correct value is selected in the dropdown. There was some hint that the same could be accomplished by placing a value in ViewData that matched the name of the field. But, I did not try that one. I was happy enough to find that I could now properly seed a default value into my model and have the dropdownlist properly rendered to show the default value selected when the view was rendered.
Who knows what other mysteries I will encounter as I embark on learning about ASP.NET MVC 3 and beyond. As I write, the beta version for MVC 4 is available. Do, I dare? We shall see.