Asp.net mvc 传入字典的模型项的类型为';System.Collections.Generic.List[CA1API.Models.Weather]';
我正在创建一个获取位置类型的应用程序 我收到这个错误Asp.net mvc 传入字典的模型项的类型为';System.Collections.Generic.List[CA1API.Models.Weather]';,asp.net-mvc,Asp.net Mvc,我正在创建一个获取位置类型的应用程序 我收到这个错误 Model item passed into the dictionary is of type 'System.Collections.Generic.List[CA1API.Models.Weather]', but this requires model item type 'System.Collections.Generic.IEnumerable [CA1API.Models.Location]'. 我已经创建了如下所示的Vi
Model item passed into the dictionary is of type 'System.Collections.Generic.List[CA1API.Models.Weather]', but this requires model item type 'System.Collections.Generic.IEnumerable [CA1API.Models.Location]'.
我已经创建了如下所示的ViewModel
名称空间CA1API.Models
{
public enum County
{
Ireland,
England,
Iceland
}
public class Location
{
public int LocationID { get; set; }
[Display(Name = "Location")]
public County LocationName { get; set; }
public double Lat { get; set; }
public double Lon { get; set; }
public int WeatherID { get; set; }
public List<Weather> Weathers { get; set; }
}
}
我的看法是这样的
public class HomeController : Controller
{
private WeatherDb db = new WeatherDb();
public ActionResult Index()
{
return View(db.Weathers.ToList());
}
}
@model IEnumerable<CA1API.Models.Location>
<div class="row">
<div class="col-md-2">
<div class="panel panel-success">
<div class="panel-heading">County</div>
<div>
<div class="panel-body" style="overflow-x:hidden; height:300px;">
@foreach (var item in Model)
{
<p>modelItem=>item.County</p>
}
</div>
</div>
</div>
</div>
@model IEnumerable
县
@foreach(模型中的var项目)
{
modelItem=>item.County
}
您的索引
视图将@model IEnumerable
用作模型,然后尝试将@model List
传递到视图
因为您尝试传递的模型没有继承,或者它不是期望接收的模型,所以它抛出了一个异常
传递到字典中的模型项的类型为
“System.Collections.Generic.List[CA1API.Models.Weather]”,但是
需要模型项类型“System.Collections.Generic.IEnumerable”
[CA1API.Models.Location]”
错误很明显。您正在传递一个
列表
,其中视图需要IEnumerable
您可能是指
返回视图(db.Locations.ToList())
而不是db.Weathers
可以添加视图索引的顶部吗?以@model开头的行代码>?您查看的是@model IEnumerable
——但您通过的是IEnumerable
。将视图更改为@model IEnumerable
(不确定视图应该显示什么,但类型必须匹配)谢谢,这个答案对我很有用