2014-09-23 57 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> 

感謝

回答

1

您需要分配給SelectList在GET AddCrew方法中使用(正如您在POST方法中所做的那樣)。請注意,如果ModelState有效(您保存並重定向,因此您沒有必要返回視圖),您不需要在POST方法中指定SelectList

+0

謝謝,這似乎是我的問題,我想知道如果您在我的數據查詢中發現任何問題?因爲我有:DataBinding:'System.String'不包含名稱爲'person'的屬性。我嘗試了所有可能的選項,但都沒有成功。 – user3539718 2014-09-24 00:33:10

+0

您的查詢僅選擇一個屬性('select person.name;'),所以'SelectList(data.ToList(),「name」,「name」);'正在創建一個基於'List '的SelectList'和試圖將值和文本屬性設置爲'string'的'id'和'name'。你需要選擇'id'和'name'屬性 – 2014-09-24 00:44:50

+0

非常感謝你的時間和幫助!它的工作原理應該如此。 – user3539718 2014-09-24 00:55:33