【问题标题】:ASP.Net MVC Razor - Display Countries Gives Error in ViewASP.Net MVC Razor - 显示国家/地区显示错误
【发布时间】:2013-03-28 07:01:55
【问题描述】:

我正在尝试列出视图中的国家/地区。我创建了一个名为 tbl_Countries 的模型,代码如下

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 li 和 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指令指定模型名称?

【问题讨论】:

  • 请展示你的观点

标签: asp.net-mvc


【解决方案1】:

您收到此错误,因为您在视图中指定了@model List,但将其传递给 List,尝试在您的视图中将其更改为 List

是的,您完全可以删除@model,但在这种情况下,您的视图不会是强类型的,因此您将无法使用智能感知

【讨论】:

    【解决方案2】:

    在模型中创建国家类型列表

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

    在索引页面设置这个List的值

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

    【讨论】:

      【解决方案3】:

      根据错误消息,您期望视图中的 List&lt;TestMVC.Models.tbl_Countries&gt; 类型的模型与您的操作方法返回的 List&lt;TestMVC.tbl_Countries&gt; 类型不同。

      要解决此问题,您可以创建一个视图期望的列表,并将您从 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 模型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-12
        • 1970-01-01
        • 1970-01-01
        • 2015-11-27
        • 2014-03-23
        • 1970-01-01
        相关资源
        最近更新 更多