如何使用(IEnumerable <selectlistitem>)ViewBag显示数据库中保存的项目

时间:2017-02-11 19:12:03

标签: c# html asp.net-mvc-4

我想显示保存在数据库中的事件,并显示包含所有可用事件的下拉列表,以便从中选择项目,

控制器:

self.tableView.separatorColor = UIColor.clear

代码:

   public ActionResult Edit(long? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        TempData["CurrentPerformanceId"] = id;
        Performance performance = db.Performances.Find(id);
        if (performance == null)
        {
            return HttpNotFound();
        }
        var performancePerformers = performance.PerformerPerformances.Select(x => x.PerformerId).ToList();
        var availablePerformers = db.Performers.Where(s => !performancePerformers.Contains(s.PerformerId)).ToList();
        CustomPerformancePerformersModel cppm = new CustomPerformancePerformersModel();
        cppm.performanceObj = performance;
        cppm.AvailablePerformers = availablePerformers.Select(x => new SelectListItem
        {
            Text = x.Name,
            Value = x.PerformerId.ToString()
        }).ToList();

        //Events Dropdown autocomplete
        var availableEvnets = db.Events.AsNoTracking().Where(s => s.Deleted == false).ToList();
        var EventDropDownList = new List<SelectListItem>();
        foreach (var item in availableEvnets)
        {
            EventDropDownList.Add(new SelectListItem { Text = item.Name, Value = item.EventId.ToString() });
        }

        //Venues Dropdown autocomplete
        var availableVenue = db.Venues.AsNoTracking().Where(s => s.Deleted == false).ToList();
        var VenueDropDownList = new List<SelectListItem>();
        foreach (var item in availableVenue)
        {
            VenueDropDownList.Add(new SelectListItem { Text = item.Name, Value = item.VenueId.ToString() });
        }

        ViewBag.EventDropDownList = EventDropDownList;
        ViewBag.VenueDropDownList = VenueDropDownList;
        ViewBag.EventId = new SelectList(db.Events, "EventId", "Name", performance.EventId);
        ViewBag.VenueId = new SelectList(db.Venues, "VenueId", "Name", performance.VenueId);
        return View(performance);
    }

生成此下拉列表,它始终以&#34; Amr Diab&#34;开头。如果另一个事件保存在数据库enter image description here

中,则为event

1 个答案:

答案 0 :(得分:1)

我只删除这两行:

    ViewBag.EventId = new SelectList(db.Events, "EventId", "Name", performance.EventId);
    ViewBag.VenueId = new SelectList(db.Venues, "VenueId", "Name", performance.VenueId);

这两行是重写EventId,保存在数据库中,列表中有第一选择

感谢所有