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!
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.
When a value is not specified (i.e. "Id"), DropDownListFor sometimes does not behave properly. Try this:
public class FooModel
{
public int Id { get; set; }
public string Text { get; set; }
}
var temp = new FooModel[]
{
new FooModel {Id = 1, Text = "Mr"}, new FooModel {Id = 2, Text = "Miss"},
new FooModel {Id = 3, Text = "Ms"}, new FooModel {Id = 4, Text = "Mrs"}
};
ViewBag.TitleList = new SelectList(temp, "Id", "Text", 2);
EDIT: other sololution
var temp = new []
{
new SelectListItem {Value = "Mr", Text = "Mr"}, new SelectListItem {Value = "Miss", Text = "Miss"},
new SelectListItem {Value = "Ms", Text = "Ms"}, new SelectListItem {Value = "Mrs", Text = "Mrs"}
};
ViewBag.TitleList = new SelectList(temp, "Value", "Text", "Miss");
来源:https://stackoverflow.com/questions/26905734/mvc-dropdownlist-selected-value-not-working