Reputation: 3665
I have gone through numerous methods of trying to set the value of a dropdownlist and must be doing something silly because none of the methods are working.
@Html.DropDownList("startTime", @Model.startTimeList, new { @class = "startTime", style = "width: 100px;" })
Its a generated list of half hour increments.
In my controller I set this string value..
model.startTime = myTime + " " + amOrPm; //ex 10:30 PM
My List looks like this.
List<SelectListItem> startTimeList = new List<SelectListItem>();
SelectListItem time12 = new SelectListItem { Text = "12:00 PM", Selected = false, Value = "12:00PM" };
startTimeList.Add(time12);
SelectListItem time12Half = new SelectListItem { Text = "12:30 PM", Selected = false, Value = "12:30PM" };
startTimeList.Add(time12Half);
My list always defaults to 12:00 PM because its the first one entered into the list. I want that if model.startTime has a value it sets to that value.
Upvotes: 0
Views: 3020
Reputation: 102743
You can use DropDownListFor
and let the Razor engine do the work of selecting the item that matches the property.
@Html.DropDownListFor(model => model.startTime, startTimeList)
The alternative would be to explicitly set Selected
on the item that matches:
startTimeList.First(item => item.Text.Equals(model.startTime)).Selected = true;
Upvotes: 3
Reputation: 4262
If you have a startTime property on your model, and the value of that property matches one of the values in the list (ie, it matches "12:00PM", or "12:30PM" but not "12:00 PM" or "12:30 PM"), then I think this should work:
@Html.DropDownListFor(model => model.startTime,
@Model.startTimeList,
new { @class = "startTime", style = "width: 100px;" })
Upvotes: 0