Jammer
Jammer

Reputation: 2410

MVC DropDownListFor selected value not being selected

I'm having some problems getting the selected value to work for a DropDownListFor.

The DropDownListFor is populated with a list of times:

// creates list of times for visit times select list
DateTime DateToday = DateTime.Today;
DateTime DateTimeStart = new DateTime(DateToday.Year, DateToday.Month, DateToday.Day, 8, 30, 0);
DateTime DateTimeEnd = new DateTime(DateToday.Year, DateToday.Month, DateToday.Day, 18, 0, 0);
List<SelectListItem> TimeFrom = new List<SelectListItem>();

while (DateTimeStart.TimeOfDay != DateTimeEnd.TimeOfDay)
{
    DateTimeStart = DateTimeStart.AddMinutes(30);
        TimeFrom.Add(new SelectListItem()
        {
        Selected = (DateTimeStart.TimeOfDay.ToString() == ViewBag.VbVisitTime),
        Text = DateTimeStart.ToString("HH:mm tt"),
        Value = DateTimeStart.TimeOfDay.ToString()
        });
}

model.TimeFromList = new SelectList(TimeFrom, "Value", "Text");

View

@Html.DropDownListFor(model => model.VisitDetails.VisitDateTime, Model.TimeFromList, "Select Time...", new { @class = "form-control" })

The selected value is set when the time of day = ViewBag.VbVisitTime, when I debug the value of ViewBag.VbVisitTime does equal a value in the dropdown list and i've also displayed the value of ViewBag.VbVisitTime on the screen and matches a value in the dropdown list so not sure why it isn't selecting the value.

Upvotes: 1

Views: 1915

Answers (1)

Jammer
Jammer

Reputation: 2410

The comments above helped me answer my own question, so thought i'd just post it in case it helps anyone else.

The Selected property of SelectListItem was indeed being ignored, so I instead created a new property in my model.

public TimeSpan? VisitTimeFrom { get; set; }

And then set the value of this in my controller

DateTime? visitTime = model.VisitDetails.VisitDate;
model.VisitDetails.VisitTimeFrom = visitTime.Value.TimeOfDay;

Then the dropdown list automatically selected the correct value for me

@Html.DropDownListFor(model => model.VisitDetails.VisitTimeFrom, Model.TimeFromList, "Select Time...", new { @class = "form-control" })

Upvotes: 1

Related Questions