2014-09-26 53 views
0

我有這個錯誤了一天以上,我真的不能修復它。我知道網上有很多關於這個話題的問題,我已經反覆閱讀,仍然沒有解決問題。 我只是學習MVC 4,所以我非常困惑。 我收到錯誤消息:MVC 4添加錯誤

具有'cabinCrewId'鍵的ViewData項的類型爲'System.Int32',但必須是'IEnumerable'類型。

任何幫助或方向將不勝感激!

我的控制器:

public ActionResult AddCrew() 
    { 
     FlightCabinCrew fcc = new FlightCabinCrew(); 
     return View(fcc); 
    } 

帖子行動:

[HttpPost] 
    public ActionResult AddCrew(FlightCabinCrew fcc) 
    { 
     if (ModelState.IsValid) 
     { 
      using (A1Context db = new A1Context()) 
      { 
       var data = from person in db.person 
          from flightcrew in db.flightcabincrew 
          from cabincrew in db.cabincrew 
          where flightcrew.cabinCrewId == cabincrew.person 
          where cabincrew.person == person.id 
          select person.name; 

       ViewBag.list = new SelectList(data.ToList(), "id", "name"); 

       db.flightcabincrew.Add(fcc); 
       db.SaveChanges(); 

       return RedirectToAction("Index"); 
      } 
     } 
     else 
     { 
      using (A1Context db = new A1Context()) 
      { 
       var data = from person in db.person 
          from flightcrew in db.flightcabincrew 
          from cabincrew in db.cabincrew 
          where flightcrew.cabinCrewId == cabincrew.person 
          where cabincrew.person == person.id 
          select person.name; 

       ViewBag.list = new SelectList(data.ToList(), "name", "name"); 
       return View(fcc); 
      } 
     } 
    } 
} 

而我的觀點:

<div class="editor-label"> 
     @Html.LabelFor(model => model.cabinCrewId) 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(model => model.cabinCrewId, (SelectList)ViewBag.list) 
     @Html.ValidationMessageFor(model => model.cabinCrewId) 
    </div> 

感謝

我知道我需要分配的SelectList到ViewBag在GET AddCre中w方法(正如我在POST方法中所做的那樣)。但我確實知道GET方法和我放入的東西是多麼的令人興奮。

如這裏要求的是人類

[Table("person")] 
public class Person 
{ 
    [Key, Column(Order = 1)] 
    public int id { get; set; } 
    public string name { get; set; } 

} 
+0

您可以添加「person」類的代碼嗎? – ekad 2014-09-26 01:48:57

+0

@ekad這裏是 – user398239 2014-09-26 01:51:45

+0

[MVC 4下拉框錯誤]的可能的副本(http://stackoverflow.com/questions/26005982/mvc-4-drop-down-box-error) – Leo 2014-09-26 01:57:47

回答

0

什麼這個問題的答案的意思是,你有兩個控制器。一,處理http get請求......

public ActionResult AddCrew(){...} 

,另一個是負責處理http post請求......

[HttpPost] 
public ActionResult AddCrew(FlightCabinCrew fcc){...} 

那麼你呈現兩種控制器方法同樣的觀點。要渲染這種觀點需要一個ViewBag對象,以便能夠在下拉列表中顯示的項目......在這裏...

@Html.DropDownListFor(model => model.cabinCrewId, (SelectList)ViewBag.list) 

您成功設定在處理後的控制器操作方法ViewBag對象請求......

ViewBag.list = new SelectList(data.ToList(), "id", "name"); 

,但你需要做的在處理GET請求,以及控制器的操作方法一樣的...就是這樣回答說什麼。 GET控制器操作方法是您原始問題中的第一個問題