无法使用模型和viewbag元素正确使用DropDownListFor

时间:2012-09-17 21:36:34

标签: asp.net-mvc-3 razor

我在ViewBag元素中设置了一个位置列表,如下所示:

    public ActionResult Create()
    {
        var db = new ErrorReportingSystemContext();
        IEnumerable<SelectListItem> items = db.Locations
          .AsEnumerable()
          .Select(c => new SelectListItem
          {
              Value =c.id.ToString(),
              Text = c.location_name
          });
        ViewBag.locations = items;
        return View();
    } 

我正试图从像这样的视图中获取ViewBag.locations中的值

    @Html.DropDownListFor(model => model.location_fk_id, ViewBag.locations);
    //@Html.DropDownListFor(model => model.location_fk_id, @ViewBag.locations);
    //@Html.DropDownListFor(model => model.location_fk_id, "locations");

但无济于事。我怎么用呢?

1 个答案:

答案 0 :(得分:3)

如果你这样做,你只需要施展它:

@Html.DropDownListFor(model => model.location_fk_id, (IEnumerable<SelectListItem>)ViewBag.locations)