【问题标题】:Using a Razor For loop on an IEnumerable ViewModel - problems accessing by index在 IEnumerable ViewModel 上使用 Razor For 循环 - 按索引访问时出现问题
【发布时间】: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 =&gt; Mapper.Map&lt;CustomerViewModel&gt;(c)).ToList());。但是,如果您不创建表单控件,则始终可以在视图中使用 foreach 循环(或者如果您是,则使用 EditorTemplate
  • @foreach 是否适合您?另外看看你的变量的大小写(小写和大写“m”)
  • @khlr 我想我可以使用 foreach ......我的最终目标是能够在循环时向列表中的每个其他项目添加一个 css 类。我想我需要以某种方式利用索引来做到这一点。

标签: c# asp.net-mvc razor asp.net-core asp.net-core-mvc


【解决方案1】:

您的模型需要IList&lt;CustomerViewModel&gt; 类型,在您的方法Index 中,您将IEnumerable&lt;CustomerViewModel&gt; 作为模型传递。 IEnumerable&lt;T&gt; 不能自动转换为IList&lt;T&gt;,所以会报错。

解决问题的简单方法是将模型转换为Index 方法中的列表。您可以为此使用 LINQ 方法 ToList()

public IActionResult Index()
{
    IList<Customer> customers = _ctx.Reviews.GetCustomers().ToList();

    // The result is converted to List using method ToList()
    return View(customers.Select(c => Mapper.Map<CustomerViewModel>(c)).ToList());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2021-12-05
    • 2021-10-10
    • 2015-01-19
    • 2021-09-08
    • 2020-03-15
    • 2015-02-14
    相关资源
    最近更新 更多