This is my VM
public class CountriesViewModel
{
public string CurrentCountry { get; set; }
public IEnumerable<Country> Countries { get; set; }
}
With my Controller
public class FiltersController : Controller
{
public ActionResult _ShipToCountry(IEnumerable<Country> countries,
string currentCountry = "AE")
{
var viewModel = new CountriesViewModel
{
Countries = countries.OrderBy(x => x.Name),
CurrentCountry = currentCountry
};
return PartialView(viewModel);
}
}
And finally the View
@Html.DropDownListFor(x => x.Countries,
new SelectList(Model.Countries.ToList(),
"Code", "Name", Model.CurrentCountry))
Where Model.CurrentCountry is the Code.
The DDL is rendered correctly
...
<option value="UA">Ukraine</option>
<option value="AE">United Arab Emirates</option>
<option value="UK">United Kingdom</option>
....
But no Country gets selected, what am I missing?
You should set CurrentCountry
prop to expression if not also you cannot get the selected country on form submit.
@Html.DropDownListFor(x => x.CurrentCountry,
new SelectList(Model.Countries.ToList(), "Code", "Name"))
This worked...
Instead of
@Html.DropDownListFor(x => x.Countries,
new SelectList(Model.Countries.ToList(),
"Code", "Name", Model.CurrentCountry))
Used
@Html.DropDownList(Model.CurrentCountry,
new SelectList(Model.Countries.ToList(),
"Code", "Name", Model.CurrentCountry))