2012-12-04 100 views
0

ASP.Net MVC 4傳遞到字典的模型項的類型爲「System.Collections.Generic.List`1 [System.Int32]」

我想填充的國家名單(數據來自國家表在DB)在下拉列表中。我得到以下錯誤:

The model item passed into the dictionary is of type 
System.Collections.Generic.List`1[System.Int32]', but this dictionary requires a model item of type 'BIReport.Models.Country'. 

我新的ASP.Net MVC,我不明白的錯誤。我覺得Index方法返回的內容與我在View中使用的模型不匹配。

型號::

namespace BIReport.Models 
{ 
    public partial class Country 
    { 
    public int Country_ID { get; set; } 
    public string Country_Name { get; set; } 
    public string Country_Code { get; set; } 
    public string Country_Acronym { get; set; } 
    } 

} 

控制器::

public class HomeController : Controller 
{ 
    private CorpCostEntities _context; 

    public HomeController() 
    { 
     _context = new CorpCostEntities(); 
    } 

    // 
    // GET: /Home/ 

    public ActionResult Index() 
    { 
     var countries = _context.Countries.Select(arg => arg.Country_ID).ToList(); 
     ViewData["Country_ID"] = new SelectList(countries); 
     return View(countries); 
    } 

} 

查看::

@model BIReport.Models.Country 
<label> 
Country @Html.DropDownListFor(model => model.Country_ID, ViewData["Country_ID"] as SelectList) 
</label> 

我要去哪裏錯了?

回答

0

您選擇CountryIDs,所以你將有一個整數列表傳入視圖。

我覺得你真的希望是這樣的:

public ActionResult Index() 
{ 
    var countries = _context.Countries.ToList(); 
    ViewData["Country_ID"] = new SelectList(countries, "Country_ID", "Country_Name"); 
    return View(); 
} 

我真的不知道爲什麼你有一個國家作爲您的視圖模型。

更新:

我仍然不知道爲什麼模型是一個國家,如果你只是要發佈所選國家的ID,你不一定需要在所有的模型(或只是有一個整數)。這將是蠻好的,但:

查看

@model MvcApplication1.Models.Country 

@Html.DropDownListFor(m => m.Country_ID, ViewData["Country_ID"] as SelectList) 
+0

我有一個國家的表,其中有很多其他列,然後Country_Name。這就是爲什麼我把國家當作模範。不知道這是否是錯誤的。順便說一句,在你的情況下,視圖代碼的外觀如何?對不起,問這個。 – shaz

+0

所以你的觀點應該是由多個國家組成的表格? –

+0

我不確定如何在MVC上下文中說它,但我試圖在我的索引頁上顯示一個帶有國家/地區列表的下拉列表。所以我有一個名爲Country的表,其中 – shaz

0

問題出現在您的視圖的第1行。改變這樣的:

@model IEnumerable<BIReport.Models.Country> 

也有沒有必要通過模型來查看,如果你已經做到了:

​​
0

當你說@model BIReport.Models.Country這意味着你的觀點是希望由單一國家的細節的典範。相反,您需要在下拉列表中顯示國家列表。因此,您應該通過視圖來查找國家詳細信息列表。 因此@model IEnumerable。

相關問題