没有类型为“IEnumerable”的 ViewData 项具有键“CompanyID”

本文关键字:ViewData CompanyID SelectListItem 类型 IEnumerable | 更新日期: 2024-11-07 12:46:38

我一直在阅读StackOverflow,但没有什么能真正帮助我解决这个问题。我正在研究一个位置模型,该模型具有来自其他几个模型的字段的 SelectLists,但每次我尝试保存时都会收到错误:

"System.Web.Mvc 中发生了类型为'System.InvalidOperationException'的异常.dll但未在用户代码中处理

其他信息:没有类型为"IEnumerable"的 ViewData 项具有键"CompanyID"。

以下是我认为的相关代码:

Views/Position/Create.cshtml

<div class="form-group">
    <label class="control-label col-md-2">Company</label>
    <div class="col-md-10">
        @Html.DropDownList("CompanyID", (SelectList)ViewBag.AllCompanies, new { @class = "form-control" })
    </div>
</div>

以下是我的控制器中的相关代码:

控制器

/位置控制器.cs

        // GET: /Position/Create
        public ActionResult Create()
        {
            //create query to find all committees
            var query = from m in db.Majors
                        orderby m.Major
                        select m;
            //execute query and store in list
            List<Majors> allMajors = query.ToList();
            //convert list to select list format needed for HTML
            SelectList allMajorsList = new SelectList(allMajors, "MajorID", "Major");
            ViewBag.AllMajors = allMajorsList;
            //create query to find all committees
            var query2 = from c in db.Companies
                        orderby c.CompanyName
                        select c;
            //execute query and store in list
            List<Company> allCompanies = query2.ToList();
            //convert list to select list format needed for HTML
            SelectList allCompaniesList = new SelectList(allCompanies, "CompanyID", "CompanyName");
            ViewBag.AllCompanies = allCompaniesList;
            //create query to find all committees
            var query3 = from i in db.Industries
                         orderby i.IndustryName
                         select i;
            //execute query and store in list
            List<Industry> allIndustries = query3.ToList();
            //convert list to select list format needed for HTML
            SelectList allIndustriesList = new SelectList(allIndustries, "IndustryID", "IndustryName");
            ViewBag.AllIndustries = allIndustriesList;
            return View();
        }
    // POST: /Position/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="PositionID,PositionTitle,PositionType,PositionLocation,PositionDeadline,PositionDescription")] Position position, int[] SelectedMajors, Int32 CompanyID, Int32 IndustryID)
    {
        //find selected committee
        Company SelectedCompany = db.Companies.Find(CompanyID);
        Industry SelectedIndustry = db.Industries.Find(IndustryID);
        //associate committee with event
        position.PositionCompany = SelectedCompany;
        position.PositionIndustry = SelectedIndustry;
        if (ModelState.IsValid)
        {
            //if there are majors to add, add them
            if (SelectedMajors != null)
            {
                foreach (int MajorId in SelectedMajors)
                {
                    Majors majorToAdd = db.Majors.Find(MajorId);
                    position.ApplicableMajors.Add(majorToAdd);
                }
            }
            db.Positions.Add(position);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(position);
    }

似乎无法弄清楚我做错了什么。任何帮助将不胜感激!

没有类型为“IEnumerable<SelectListItem>”的 ViewData 项具有键“CompanyID”

您的问题是if (ModelState.IsValid)很可能是假的..并且当您从POST返回View时,您没有重置ViewBag值。

如果 ViewBag 值为 null,则视图将在您的 ViewData 中查找与属性名称匹配的内容,这就是您收到该错误的原因。 如果您在 [HttpGet] 操作中注释所有代码并在那里返回 View,则会收到相同的错误。

您应该尝试将所有这些代码移动到私有空白中。

private void LoadViewBag() 
{
        //create query to find all committees
        var query = from m in db.Majors
                    orderby m.Major
                    select m;
        //execute query and store in list
        List<Majors> allMajors = query.ToList();
        //convert list to select list format needed for HTML
        SelectList allMajorsList = new SelectList(allMajors, "MajorID", "Major");
        ViewBag.AllMajors = allMajorsList;
        //create query to find all committees
        var query2 = from c in db.Companies
                    orderby c.CompanyName
                    select c;
        //execute query and store in list
        List<Company> allCompanies = query2.ToList();
        //convert list to select list format needed for HTML
        SelectList allCompaniesList = new SelectList(allCompanies, "CompanyID", "CompanyName");
        ViewBag.AllCompanies = allCompaniesList;
        //create query to find all committees
        var query3 = from i in db.Industries
                     orderby i.IndustryName
                     select i;
        //execute query and store in list
        List<Industry> allIndustries = query3.ToList();
        //convert list to select list format needed for HTML
        SelectList allIndustriesList = new SelectList(allIndustries, "IndustryID", "IndustryName");
        ViewBag.AllIndustries = allIndustriesList;
}

然后将 GET 操作更改为

    // GET: /Position/Create
    public ActionResult Create()
    {
        LoadViewBag();
        return View();
    }

然后将"发布"操作更改为

// POST: /Position/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="PositionID,PositionTitle,PositionType,PositionLocation,PositionDeadline,PositionDescription")] Position position, int[] SelectedMajors, Int32 CompanyID, Int32 IndustryID)
{
    //find selected committee
    Company SelectedCompany = db.Companies.Find(CompanyID);
    Industry SelectedIndustry = db.Industries.Find(IndustryID);
    //associate committee with event
    position.PositionCompany = SelectedCompany;
    position.PositionIndustry = SelectedIndustry;
    if (ModelState.IsValid)
    {
        //if there are majors to add, add them
        if (SelectedMajors != null)
        {
            foreach (int MajorId in SelectedMajors)
            {
                Majors majorToAdd = db.Majors.Find(MajorId);
                position.ApplicableMajors.Add(majorToAdd);
            }
        }
        db.Positions.Add(position);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    LoadViewBag();
    return View(position);
}