2017-02-02 119 views
1

我正在做ASP .NET Web應用程序教程作爲項目的一部分,並且我遇到了錯誤消息這篇文章的標題沒有類型爲'IEnumerable <SelectListItem>'的ViewData項目具有關鍵字'SelectedDepartment'

我想在課程頁面顯示一個下拉菜單來選擇所選課程的一個部門。 enter image description here

這是工作的罰款之前,我開始與GenericRepository的UnitOfWork類的工作。我必須在我的Views/Course/Index.cshtml以下注釋掉以下代碼,以便課程頁面能夠正常工作。

@using (Html.BeginForm()) 
{ 

    @*<p> 
     Select Department: @Html.DropDownList("SelectedDepartment", "All") 
     <input type="submit" value="Filter" /> 
    </p>*@ 
} 

現在我有一個ViewResult索引代碼根據教程。

public ViewResult Index() 
{ 
    var courses = unitOfWork.CourseRepository.Get(includeProperties: "Department"); 
    return View(courses.ToList()); 
} 

我做庫

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()); 
} 

在我CourseController我有一個PopulateDepartmentsDropDownList方法,其中可能需要改變以前出現過此的ActionResult指數方法,但我一直在玩了,但到目前爲止還沒有成功。

private void PopulateDepartmentsDropDownList(object selectedDepartment = null) 
{ 
    var departmentsQuery = unitOfWork.DepartmentRepository.Get(orderBy: q => q.OrderBy(d => d.Name)); 

    ViewBag.DepartmentID = new SelectList(departmentsQuery, "DepartmentID", "Name", selectedDepartment); 
} 

請解決此問題的任何提示。

+0

你可以發佈你的這個視圖的操作方法嗎? 'Index ActionResult'具體爲 –

+0

我有一個ViewResult的Index方法而不是ActionResult。 – Truecolor

+0

所以在ViewResult是你聲明'ViewBag.DepartmentID'的地方 –

回答

0

我只是在Controller編輯我的Get方法(Index方法),包括過濾器。

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

您正在指定DropDown列表的名稱爲SelectedDepartment,但在您的操作中您有ViewBag.DepartmentID,它持有SelectList對象。您沒有在視圖中使用填充的SelectList,因此發生的情況是DropDownList正在查看ViewBag中的SelectedDepartment關鍵字,其DropDown列表項將填充,這是DropDownList幫助器方法的默認行爲。

您需要使用ViewBag.DepartmentID在你的DropDownList幫手,如:

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

它有''所有「'說」下的紅色錯誤行不能從'字符串'轉換爲'Systems.Collections.Generic.IEnumerable 」'

選擇部門:@ Html.DropDownList( 「SelectedDepartment」, 「全部」,作爲ViewBag.DepartmentID的SelectList)

' – Truecolor

+0

OP提供的C#代碼不是他的動作..只是一個方法來填充下拉列表.. –

+0

也沒有重載的方法'Html.DropDownList',可以包含2個字符串,然後選擇列表..選擇列表應該被放置在「全部」之前 –

相關問題