2
votes

My select list isn't selecting the default object being brought in through code.

I first create my SelectList like so:

public SelectList CreateSelectList(object objSelected = null)
{
  return new SelectList(GetAll().OrderBy(s => s.NumericalValue), "PeriodID", "Name", objSelected);
}

My objSelected gets filled with a Guid that's associated with the PeriodID.

Inside my controller I define my viewbag variable to the new select list.

public ActionResult Edit(Guid id)
{
  Classroom classroom = classroomRepository.GetByID(id);
  ViewBag.PeriodID = periodRepository.CreateSelectList(classroom.PeriodID);
  return View(classroom);
}

Then in my View here's how I'm displaying my SelectList:

<div class="control-group">
  @Html.LabelFor(model => model.PeriodID, "Period", new { @class = "control-label" })
  <div class="controls">
      @Html.DropDownListFor(model => model.PeriodID, ViewBag.PeriodID as SelectList, String.Empty, new { @class = "span3" })
      @Html.ValidationMessageFor(model => model.PeriodID)
  </div>
</div>
1
and what should be the default object? - Thousand
The default object should be an item called "Fourth", associated with the Guid being passed in. The problem is, nothing is being displayed in the View, it's just the first item in the SelectList. - Wesley
and what's the default object being shown now? if i understand correctly, the default value has to come from the list you are returning? - Thousand

1 Answers

7
votes

You have two problems here. First, this:

@Html.DropDownListFor(model => model.PeriodID, ViewBag.PeriodID as SelectList, 
      String.Empty, new { @class = "span3" })

Change ViewBag.PeriodID to ViewBag.Periods or ViewBag.PeriodList. This is confusing, and there are a number of situations in which MVC will get confused if you use the same named object. It's just best to make sure everything is named differently.

Second, The SelectList class ignores the selecteditem member of the SelectListItem. It's not used at all. DropDownListFor will take the value of model.PeriodID and make it the selected value. However, I see in your code that those should be the same so I'm guessing the naming may be a factor here.