MVC DropDownList selected value not working

Ruchan picture Ruchan · Nov 13, 2014 · Viewed 22.7k times · Source

I am using MVC 5.

I have my ViewBag for list as

ViewBag.TitleList = new SelectList((new string[] { "Mr", "Miss", "Ms", "Mrs" }), contact.Title);
//contact.Title has selected value.

then I tried converting the array to SelectListItem ( to no avail)

On the View it looks like

@Html.DropDownListFor(model => model.Title, ViewBag.TitleList as SelectList, "Select")

also I tried

@Html.DropDownList("Title", ViewBag.TitleList as SelectList, "Select")

The list loads successfully but the Selected Value is Not selected. How to Fix this problem?

Update The culprit was ViewBag.Title matching my model.Title. Renamed my model property to something else and it worked. Arrgh!

Answer

Zabavsky picture Zabavsky · Nov 13, 2014

Set value of the Title property in the controller:

ViewBag.TitleList = new SelectList(new string[] { "Mr", "Miss", "Ms", "Mrs" });
viewModel.Title = "Miss"; // Miss will be selected by default

Another possible reason (and the correct one, based on the comments below) is that ViewData["Title"] is overridden by another value. Change name of the Title property to any other and everything should work.