This has been reduced a bit, but essentially I have a model that looks something like this:
public class PersonCreateEditViewModel { public string Title { get; set; } public IEnumerable<SelectListItem> Titles { get; set; } }
and on my edit page I want to display the current name of the person in DropDownList so that we can change the name. This code is as follows:
@Html.DropDownListFor(model => model.Title, new SelectList(Model.Titles, "Value", "Text", Model.Title))
and I fill it in my action like this, getting a bunch of lines:
IEnumerable<SelectList> titles = somelistoftitles.Select( c => new SelectListItem { Value = c, Text = c }; var viewModel = new PersonCreateEditViewModel() { Title = model.Title, Titles = sometitles }; return View(viewModel);
and this populates DropDownList with values, but does not select the current user. So, I'm obviously doing something wrong. If you look at the basic html, I see that the selected attribute is not set for the parameter corresponding to the Title person. I thought I would specify Model.Title where the third argument would select it.
Ideas?
Update
I added the setting of the selected property as qntmfred, proposed below, and this will set the list to true, but <option> does not have the selected attribute on it.
solvable
So that was subtle. I just got a ViewBag entry titled βTitleβ - something like this:
@{ ViewBag.Title = "Edit Person" }
and this, obviously, made the choice not work, since my model also has the Title property. I solved the problem by renaming the property.