I had a viewmodel like so:
[Required] public string Title { get; set; } public List<SelectListItem> TitleSelectList { get { var selectList = new List<SelectListItem>(); selectList.AddRange(new string[] { "Mr", "Mrs", "Miss", "Ms", "Dr", "Other" }.Select(item => new SelectListItem() { Text = item, Value = item })); selectList.Insert(0, new SelectListItem { Text = "Choose...", Value = "" }); return selectList; } }
and in my View, I was showing it like this:
@Html.DropDownListFor(model => model.Title, Model.TitleSelectList)
HOWEVER, in my View, I also had this lurking:
@{ ViewBag.Title = "My Lovely Page"; }
Yup, with DropDownListFor at least, ViewBag properties are used in preference to model properties when MVC tries to find the selected value. It couldn't find "My Lovely Page" in the SelectList, and so nothing was selected. When I changed my ViewBag property to ViewBag.PageTitle instead, everything started working properly.
Thanks a lot!
ReplyDeleteThat was a great help - scoured the web for hours looking for this. Good luck with your web development.
ReplyDeletethanks this look me ages to find. u are a star
ReplyDeleteYou are really a gems....thaks for providing us such simple solution
ReplyDelete