Razor MVC下拉列表未显示所选值

时间:2014-05-22 17:15:02

标签: asp.net-mvc entity-framework razor

我可以从我的下拉列表中成功选择一个值,并正确保存到数据库中。但是,当我返回到我的视图页面时,下拉列表看起来没有先前选择的值。为什么不显示所选值?

查看:

@Html.DropDownList("UnitOfMeasure",ViewData["UnitOfMeasure"] as SelectListItem[], new { @class = "form-control" })

控制器:

        [HttpGet]
    public ActionResult Edit(int id)
    {
         this.ViewBag.UnitOfMeasure = this.GetUomList();
    }


        private IEnumerable<SelectListItem> GetUomList()
    {
        List<SelectListItem> uomList = new List<SelectListItem>();            
        uomList.Add(new SelectListItem() { Value = "", Text = "Select..." });

        uomList.Add(new SelectListItem() { Text = "CC" });
        uomList.Add(new SelectListItem() { Text = "CF" });
        return uomList;
    }

2 个答案:

答案 0 :(得分:2)

您需要选择具有Selected属性的项目:

uomList.Add(new SelectListItem() { Text = "CC", Selected = true });

答案 1 :(得分:1)

您必须根据存储在数据库中的内容将项目标记为已选中。以下是您可以做的事情:

private IEnumerable<SelectListItem> GetUomList()
{
    //Get selected Value or text... whatever you are storing in the db
    // I am assuming selectedText is being stored in the database
    var selectedValueOrText = GetThisFromDatabase();

    List<SelectListItem> uomList = new List<SelectListItem>();            
    uomList.Add(new SelectListItem() { Value = "", Text = "Select..." });

    uomList.Add(new SelectListItem() { Text = "CC",Selected = selectedValueOrText =="CC" });
    uomList.Add(new SelectListItem() { Text = "CF",Selected = selectedValueOrText =="CF" });

   return uomList;
}

<强>更新      上面方法的替代版本。 (IMO改进:))

 private IEnumerable<SelectListItem> GetUomList()
 {
      //Get selected Value or text... whatever you are storing in the db
      // I am assuming selectedText is being stored in the database
      var selectedValueOrText = GetThisFromDatabase();
      var uomList = new List<string>
      {
          "Select...",
          "CC",
          "CF"
      };
      return uomList.Select(l => new SelectListItem
      {
          Text = l,
          Selected = selectedValueOrText == l
      });

  }

如果您展示了从数据库中获取值的方法,我可以进一步简化/改进我的答案。