2012-12-04 99 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。

相关问题