Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC DropDownList selected value not working

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!

like image 282
Ruchan Avatar asked Nov 13 '14 09:11

Ruchan


1 Answers

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.

like image 92
Zabavsky Avatar answered Oct 20 '22 01:10

Zabavsky