2015-02-09 38 views
1

我是MVC的新手。我試圖綁定一個下拉列表,但面臨一個問題。無法綁定MVC中的DropDownList

以下數據層的代碼:

public List<DataLayer.Customer> GetCustomers() 
     { 
      return obj.Customers.ToList(); 

     } 

控制器代碼:

[Authorize] 
     public ActionResult CreateOrder() 
     { 
      ViewBag.Message = "Crearte Order"; 
      ViewBag.Customers = manageOrder.GetCustomers(); 
      return View(); 
     } 

查看代碼:

@Html.DropDownList("SelectedMovieType", (IEnumerable<SelectListItem>) ViewBag.Customers) 

獲得以下錯誤,當它試圖綁定DropDownList

可以投射'System.Collections.Generic.List 1[DataLayer.Customer]' to type 'System.Collections.Generic.IEnumerable 1 [System.Web.Mvc.SelectListItem]'類型的對象。

讓我知道,我怎麼能得到這個問題。

+5

我建議,因爲有很多關於這個職位的周圍更多的瀏覽。 – SOfanatic 2015-02-09 14:16:13

+0

如果你對我的問題有答案,你會怎麼做。感謝評論。 – 2015-02-09 14:19:57

+0

錯誤告訴你到底是什麼問題。當編譯器說它不能將它從一種類型轉換爲另一種類型時,這意味着你的源類型不能被轉換爲...因爲它是完全不同的而且不兼容。您需要創建一個兼容的數據項(例如創建SelectListItem的新集合)。 – 2015-02-09 14:58:10

回答

4

ViewBag.Customers應該是List<SelectListItem>類型。

控制器代碼:

ViewBag.Customers = manageOrder.GetCustomers().Select(c => new SelectListItem { Text = c.TextProperty, Value = c.ValueProperty }).ToList(); 

查看代碼:

@Html.DropDownList("Customers") 
+0

謝謝,它的工作原理。 – 2015-02-09 15:16:32