2014-06-09 28 views
0

我做了一個Dropdownlist,其中包含來自數據庫的值,它在單獨的View中非常有用。但是,當我試圖表明我的局部視圖DROPDOWNLIST它不工作,我得到異常:「有型‘的IEnumerable’有沒有ViewData的項目的關鍵‘ID’」爲什麼我的Dropdownlist在MVC的部分視圖中不起作用?

這裏是我的代碼:

//it's my Model 
namespace TC.Models 
{ 
    public class TypesQuestionBL 
    { 
     public System.Guid Id { get; set; } 
     public string Name { get; set; } 
     public IEnumerable<SelectListItem> Types { get; set; } 
    } 
} 

//it's my Controller 
namespace TC.Controllers 
{ 
    public class DropDownController : Controller 
    { 
     ExaminationsEntities db = new ExaminationsEntities(); 

     public ActionResult Index() 
     { 
      SelectList typelist = new SelectList(db.TypesQuestions.ToList(), "Id", "Name"); 
      ViewData["Types"] = typelist; 
      return View(); 
     } 

     protected override void Dispose(bool disposing) 
     { 
      db.Dispose(); 
      base.Dispose(disposing); 
     } 
    } 
} 

//it's my Partial View 
@model TC.Models.TypesQuestionBL 
@Html.DropDownList("Id", (IEnumerable<SelectListItem>) ViewData["Types"]) 

//it's my View 
@Html.Partial("~/Views/DropDown/Index.cshtml") 

回答

0

更新

更仔細地觀察它看起來像你試圖渲染使用索引視圖的局部視圖。您正嘗試重新呈現您當前顯示爲相同視圖的部分視圖,這可能是您遇到問題的原因。視圖中的行需要從@ Html.Partial(「〜/ Views/DropDown/Index.cshtml」)更改爲@ Html.Partial(「〜/ Views/DropDown/_MyDropDownListPartialViewNameHere.cshtml」)。你有一個單獨的部分視圖創建正確嗎?你可以發佈文件名嗎?


要設置ViewData["Types"]SelectList對象,當你需要將其設置爲一個IEnumerable<SelectListItem>對象。

食指動作應該是這樣的:

public ActionResult Index() 
{ 
    var typelist = db.TypesQuestions.Select(x => new SelectListItem 
    { 
     Text = x.Name, 
     Value = x.Id.ToString() 
    }).ToList(); 
    ViewData["Types"] = typelist; 
    return View(); 
} 
+0

感謝您的回答,我想這一點,但我有同樣的問題。 – Illia

+0

我認爲動態屬性不能綁定到html助手 –

相關問題