I have this in my controller:
[Route("Checkout")]
public ActionResult Checkout()
{
var sb = new ShoppingBagViewModel();
sb.DestinationCountry = "Netherlands"; // I hoped that this was sufficient
sb.CountriesSl.Single(c => c.Text.Equals("Netherlands", StringComparison.InvariantCultureIgnoreCase)).Selected = true;
return View(sb);
}
Quick watch in Visual Studio confirmed that the CountriesSl (which is of type List<SelectListItem>
) has a selected value. (netherlands)
This is my razor view:
@Html.DropDownListFor(m => m.DestinationCountry, Model.CountriesSl)
DestinationCountry
is also a string prop in my viewmodel. I know that there are a lot of similar questions, but I have looked at a lot of them and I just do not see it. I also tried:
@Html.DropDownListFor(m => Model.DestinationCountry, Model.CountriesSl)
Please do not just give me the answer, but also explain what my mistake is.
edit to make clear what the problem is: I get a nice option list in my razor view, but there is no item "selected" just the first one. When I look at the generated html, there is no selected item too.
edit for Ric
public List<SelectListItem> CountriesSl
{
get
{
List<SelectListItem> _countries = HttpContext.Current.Cache["slCountries"] as List<SelectListItem>;
if (_countries == null)
{
_countries = new List<SelectListItem>();
foreach (string s in System.IO.File.ReadLines(System.Web.Hosting.HostingEnvironment.MapPath("~/tmpwrite/countries.csv")))
{
var tmp = s.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
_countries.Add(new SelectListItem() { Text = tmp[1], Value = tmp[0], Selected = false });
}
HttpContext.Current.Cache.Add("slCountries", _countries.OrderBy(c => c.Text).ToList(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(24, 0, 0), System.Web.Caching.CacheItemPriority.Normal, null);
}
return _countries;
}
}
DropDownListFor
tries to automatically match the value of the receiving property in the provided enumeration. I also had problems with this in the beginning.
Instead provide any list of entities in the viewmodel. I usually use something like IDictionary<int, string>
. Then create the dropdown like this:
Html.DropDownListFor(m=>m.DestinationCountry, new SelectList(Model.Countries, "Key", "Value"))
Then the SelectList will automagically set the correct option where its Key matches DestinationCoutry.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments