2 Sept 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.

4 comments:

  1. Anonymous10:26 am

    Thanks a lot!

    ReplyDelete
  2. Anonymous6:10 pm

    That was a great help - scoured the web for hours looking for this. Good luck with your web development.

    ReplyDelete
  3. Anonymous3:52 pm

    thanks this look me ages to find. u are a star

    ReplyDelete
  4. You are really a gems....thaks for providing us such simple solution

    ReplyDelete

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!