2013-08-23 75 views
0

在控制器:有類型的無ViewData的項目 '的IEnumerable <SelectListItem>' 具有鍵 'aboutcar.Doors'

ViewBag.Doors = new SelectList(new[] 
              { 
               new {ID = 1, Name="1-Door"}, 
               new {ID = 2,Name="2-Doors"}, 
               new {ID = 3,Name="3-Doors"}, 
               new {ID = 4,Name="4-Doors"}, 
               new {ID = 5,Name="5-Doors"}, 
               new {ID = 6,Name="6-Doors"}, 
               new {ID = 7,Name="7-Doors"} 
              }, 
          "ID", "Name"); 

鑑於:

@Html.DropDownListFor(model => model.aboutcar.Doors, (SelectList)ViewBag.Doors, "--Select--") 

當模型不驗證並且它應該再次重定向到這個視圖,然後發生這個錯誤。

+0

是什麼是aboutcar? – ckv

+0

aboutcar是一個嵌套在名爲AutoAdvert的主視圖模型中的類,aboutcar具有名爲Doors的屬性 –

+0

它在Get動作中正常工作,但在Post動作中給出了上述錯誤 –

回答

1

檢查您的[HttpPost]方法。我有同樣的錯誤。它導致我忘了創建ViewBag。 屬性在我的[HttpPost]方法的其他塊中。例如:

[HttpPost] 
    public ActionResult Edit(Model model) 
    { 
     if (ModelState.IsValid) 
     { 
      //TO DO 
     } 
     else 
     { 
      ViewBag.Doors = new SelectList(new[] 
             { 
              new {ID = 1, Name="1-Door"}, 
              new {ID = 2,Name="2-Doors"}, 
              new {ID = 3,Name="3-Doors"}, 
              new {ID = 4,Name="4-Doors"}, 
              new {ID = 5,Name="5-Doors"}, 
              new {ID = 6,Name="6-Doors"}, 
              new {ID = 7,Name="7-Doors"} 
             }, 
         "ID", "Name"); 
      ViewBag.Error = "Error"; 
      return View("Edit"); 
     } 
    } 

如果發生重定向,它將導致ViewBag變爲null。

相關問題