【发布时间】:2016-09-24 06:00:22
【问题描述】:
我知道您在使用 IEnumerable<T> 时无法按索引访问值。
这是我的看法:
@model IList<CustomerViewModel>
@for (int i = 0; i < Model.Count - 1; i++)
{
@Model[i].Name
}
请注意我需要如何创建IList 类型的ViewModel 才能使用索引。
这是我的控制器:
public IActionResult Index()
{
IList<Customer> customers = _ctx.Reviews.GetCustomers().ToList();
return View(customers.Select(c => Mapper.Map<CustomerViewModel>(c)));
}
我收到一条错误消息,指出传递给 ViewDataDictionary 的模型项不正确。
这是有道理的,因为我猜 IQueryable 正在进入?这就是为什么我试图保留 IEnumerable 类型的 ViewModel 并仍然使用 for 循环。
【问题讨论】:
-
return View(customers.Select(c => Mapper.Map<CustomerViewModel>(c)).ToList());。但是,如果您不创建表单控件,则始终可以在视图中使用foreach循环(或者如果您是,则使用EditorTemplate) -
@foreach是否适合您?另外看看你的变量的大小写(小写和大写“m”) -
@khlr 我想我可以使用 foreach ......我的最终目标是能够在循环时向列表中的每个其他项目添加一个 css 类。我想我需要以某种方式利用索引来做到这一点。
标签: c# asp.net-mvc razor asp.net-core asp.net-core-mvc