C# 没有具有键“SelectedDepartment”的“IEnumerable”类型的ViewData项

C# 没有具有键“SelectedDepartment”的“IEnumerable”类型的ViewData项,c#,asp.net-mvc,C#,Asp.net Mvc,作为一个项目的一部分,我正在学习ASP.NETWeb应用程序教程,我在这篇文章的标题中遇到了一条错误消息 我试图在课程页面中显示一个下拉菜单,为所选课程选择一个系。 在我开始使用GenericRepository和UnitofWork类之前,它工作得很好。我必须在我的视图/Course/Index.cshtml中注释掉下面的代码,以便课程页面能够正常工作 @using (Html.BeginForm()) { @*<p> Select Department

作为一个项目的一部分,我正在学习ASP.NETWeb应用程序教程,我在这篇文章的标题中遇到了一条错误消息

我试图在课程页面中显示一个下拉菜单,为所选课程选择一个系。

在我开始使用GenericRepository和UnitofWork类之前,它工作得很好。我必须在我的视图/Course/Index.cshtml中注释掉下面的代码,以便课程页面能够正常工作

@using (Html.BeginForm())
{

    @*<p>
        Select Department: @Html.DropDownList("SelectedDepartment", "All")
        <input type="submit" value="Filter" />
    </p>*@
}
在做存储库之前,我有这个ActionResult索引方法

public ActionResult Index(int? SelectedDepartment)
{
    var departments = db.Departments.OrderBy(q => q.Name).ToList();
    ViewBag.SelectedDepartment = new SelectList(departments, "DepartmentID", "Name", SelectedDepartment);
    int departmentID = SelectedDepartment.GetValueOrDefault();

    IQueryable<Course> courses = db.Courses
        .Where(c => !SelectedDepartment.HasValue || c.DepartmentID == departmentID)
        .OrderBy(d => d.CourseID)
        .Include(d => d.Department);
    //var sql = courses.ToString();
    return View(courses.ToList());
}

请提供解决此问题的任何提示

您正在指定要选择的部门的下拉列表的名称,但在操作中,您有保存SelectList对象的ViewBag.DepartmentID。您没有在视图中使用已填充的SelectList,因此DropDownList正在ViewBag中查找要填充的下拉列表项的键SelectedDepartment,这是DropDownList帮助器方法的默认行为

您需要在DropDownList帮助程序中使用ViewBag.DepartmentID,如:

@Html.DropDownList("selectedDepartment","All",ViewBag.DepartmentID as SelectList)

我只需要在控制器中编辑Get方法和Index方法,以包含过滤器

 bool hasValue = SelectedDepartment.HasValue;
 var courses = courseService.ListCourses(hasValue,departmentID);

它在所有语句下都有一条红色错误线,表示无法从“字符串”转换为“Systems.Collections.Generic.IEnumerable” 选择Department:@Html.DropDownListSelectedDepartment,All,ViewBag.DepartmentID作为SelectList

OP提供的C代码不是他的操作。。只是一个填充dropdownlist的方法。另外,Html.dropdownlist没有一个重载方法可以包含两个字符串,然后是一个selectlist。。selectlist应该放在AllI不在我的电脑上之前,我一回来就会更新post。您可以发布此视图的操作方法吗?Index ActionResult为Index方法指定了一个ViewResult,而不是ActionResult。因此,在ViewResult中声明ViewBag.DepartmentID
@Html.DropDownList("selectedDepartment","All",ViewBag.DepartmentID as SelectList)
 bool hasValue = SelectedDepartment.HasValue;
 var courses = courseService.ListCourses(hasValue,departmentID);