MVC4 SelectList not selected default object

时间秒杀一切 提交于 2019-12-12 19:13:05

问题


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:


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.



来源:https://stackoverflow.com/questions/12655479/mvc4-selectlist-not-selected-default-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!