2 Sep 2011

MVC 3 DropDownListFor not selecting an item (Title property of model)

Have you got a problem with MVC 3 where your model has a property that is definitely set, but when you use it in a DropDownListFor, the value doesn't get selected from your SelectList? Me too, and I've solved it.

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.

1 comments: