2013-03-28 194 views
0

我想列出視圖中的國家。我創建了一個名爲tbl_Countries的模型,代碼是ASP.Net MVC剃刀 - 顯示器國家給出錯誤的視圖

public class tbl_Countries 
{ 
    public int ID { get; set; } 
    public string Country_Name { get; set; } 
} 

我有一個名爲Home的控制器,其代碼如下。我已經創建了數據庫TESTDB的EDMX文件

public ActionResult Index() 
{    
    TestDBEntities TestdbContext = new TestDBEntities(); 
    var countries = TestdbContext.tbl_Countries.ToList(); 
    return View(countries); 
} 

下面是我查看代碼 @model的IList 顯示使用UL裏用foreach

的國家。如果我運行該應用程序正在此錯誤:

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[TestMVC.tbl_Countries]', 
but this dictionary requires a model item of type 'System.Collections.Generic.IList1[TestMVC.Models.tbl_Countries] 

我只想顯示在視圖中的國家列表,我想知道 沒有創建模型類是否可以綁定網格? 是否必須使用@model指令來指定型號名稱?

+0

請展現您的觀點 – 2013-03-28 09:04:46

回答

0

,因爲你在你看來@model名單中指定。您得到這個錯誤」,但傳遞給它的列表,試圖改變它在視圖中列出

是的,你可以刪除@model可言,但在這種情況下,你的觀點不會被強類型的,所以你將無法使用INTELLI感

0

模型

public List< tbl_Countries> country{get;set;} 

創建國家類型的列表在索引頁面設置名單的值

public ActionResult Index() 
    {    
    TestDBEntities TestdbContext = new TestDBEntities(); 
    tbl_Countries objModel=new tbl_Countries(); 
    objModel.country = TestdbContext.tbl_Countries.ToList(); 
    return View(objModel); 
    } 
0

根據錯誤消息,您期待的視圖中類型爲List<TestMVC.Models.tbl_Countries>的模型與您的操作方法返回的List<TestMVC.tbl_Countries>類型不同。

要解決此問題,您可以創建視圖所需的列表並將您從Entity Framework獲得的數據映射到該列表。

例如:

public ActionResult Index() 
{    
TestDBEntities TestdbContext = new TestDBEntities(); 
var countries = new List<TestMVC.Models.tbl_Countries>(); 
countries = (from country in TestdbContext.tbl_Countries 
       select new TestMVC.Models.tbl_Countries 
       { 
        Country_Name = country.Country_Name 
       }).toList(); 

return View(countries); 
} 

要單獨視圖的邏輯和數據訪問是一個很好的做法,型號分別獨立地從你的數據模型,從模型EF在您的示例。