It seems like this question has been asked too many times. But this is driving me nuts.
This is my (simplified) model.
public class UserEditModel
{
[Required]
public string Title { get; set; }
private IEnumerable<SelectListItem> _titleList;
public IEnumerable<SelectListItem> TitleList
{
get { return _titleList.Select(x => new SelectListItem {
Selected = (x.Value == Title),
Text = x.Text,
Value = x.Value
});
}
set { _titleList = value; }
}
}
The Text
and Value
properties of each SelectListItem
in the TitleList
member are identical. For example:
new SelectListItem { Text = "Mr", Value = "Mr" }
When the following code is posted, the correct Title
value is bound to the model, but whenever the model is pushed to the view in response to a POST or a GET, the selected value is not set on the dropdownlist, even though all the intellisense shows that the correct values are present.
@Html.DropDownListFor(x => x.Title, Model.TitleList)
I have ensured that the code is correct based on several articles and several SO answers, so I am stumped.
Any suggestions?
Update:
For completeness, this is the action and supporting method:
[HttpGet]
public ActionResult Edit(int id)
{
var user = _userService.Get(id);
var model = new UserEditModel()
{
...
Title = user.Title,
TitleList = ListTitles()
};
return View(model);
}
private IEnumerable<SelectListItem> ListTitles()
{
var items = new[] {
new SelectListItem() {Text = "Mr", Value = "Mr" },
new SelectListItem() {Text = "Mrs", Value = "Mrs"},
new SelectListItem() {Text = "Ms", Value = "Ms"},
new SelectListItem() {Text = "Miss", Value = "Miss"},
new SelectListItem() {Text = "Professor", Value = "Professor"},
new SelectListItem() {Text = "Dr", Value = "Dr" }
};
return items;
}
As you see there is nothing fancy, just a straightforward implementation.