Data:
var countries = new Dictionary<string,string>();
countries.Add("AF","Afghanistan");
countries.Add("US","United States");
countries.Add("FR","France");
Razor:
@Html.DropdownList("Countries",new SelectList(countries, "key", "value", "US"), "Select Country")
Issue: in my razor, I'm specifying "US"
for the selectedValue, and "Select Country"
for optionLabel. I expect this to insert "Select Country"
as the first item in the dropdown, AND have "US"
already selected for me.
What actually happens: "Select Country"
is inserted, but "US"
is NOT selected. "Select Country"
is.
Question: can I have both? Where Razor injects "Please Select"
, but also pre-selects "US"
as the default?
Please note: I'm getting the data from a table in my database, so I'd prefer not to have an actual row in there with "Please select", or have to insert it myself into the dictionary. It's easier to do Model.Countries = dbRepo.GetCountries() in my controller vs. declaring an empty dictionary, adding "Please Select", then looping thru .GetCountries() and adding to the original dictionary before setting it to Model.Countries for my view.
Thanks!
The answer here: ASP.Net Html.DropDownList Selected Element not Selected could also be the solution.
You use "Countries" for the name of the dropdown and "countries" as the name of the SelectList. Try renaming one or the other to something different.
for people looking for a list of countries, this will help
I know this post is old, but for people looking for list of coutries this is the easy way :
This should work. No idea why it doesn't because you haven't shown your actual code. Probably there's no option with
key = "US"
in your actual dataset.But anyway let me illustrate with an example the approach that I would recommend which is to use a view model and a strongly typed helper
DropDownListFor
helper.Model:
Controller:
View (
~/Views/Home/Index.cshtml
):Result: