Data:
var countries = new Dictionary();
countries.Add(\"AF\",\"Afghanistan\");
countries.Add(\"US\",\"United States\");
cou
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:
public class CountriesViewModel
{
public string SelectedCountryCode { get; set; }
public IEnumerable Countries { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new CountriesViewModel();
// TODO: obviously those will come from your database
model.Countries = new[]
{
new SelectListItem { Value = "AF", Text = "Afghanistan" },
new SelectListItem { Value = "US", Text = "United States" },
new SelectListItem { Value = "FR", Text = "France" },
};
// Preselect the option with Value = "US"
// Make sure you have such option in the Countries list
model.SelectedCountryCode = "US";
return View(model);
}
}
View (~/Views/Home/Index.cshtml
):
@model CountriesViewModel
@Html.DropDownListFor(
x => x.SelectedCountryCode,
Model.Countries,
"Select Country"
)
Result: