asp.net-mvc - 如何将索引应用于 IEnumerable 表达式类型并在 razor View 中并排显示数据

标签 asp.net-mvc razor indexing foreach

我正在开发一个 Asp.net MVC 应用程序,遇到了一个场景,我必须在两列中显示内容(即并排),我在 google 上搜索并找到了一个解决方案。我尝试过,但是徒劳的尝试。 我试过这个方法

@model IEnumerable<MvcApplication1.tblTest>

@{

ViewBag.Title = "Index";

Layout = "~/Views/Shared/_Layout.cshtml";

}

<h2>Index</h2>


<table>
    <tr>
    <th>
        testId
    </th>
    <th>
        testName
    </th>
    <th>
        testDescription
    </th>
    <th></th>
</tr>

@for (var i = 0; i < Model.Count(); i+=2 )
{
<tr>
    <td>
       @Model[i].testId
    </td>


</tr>
}

</table>

但是我遇到了编译错误 -- 编译错误

描述:编译服务此请求所需的资源期间发生错误。请查看以下具体错误详细信息并适当修改您的源代码。

Compiler Error Message: CS0021: Cannot apply indexing with [] to an expression of type       

'System.Collections.Generic.IEnumerable<MvcApplication1.tblTest>'

Source Error:


Line 27:     <tr>
Line 28:         <td>
Line 29:            @Model[i].testId
Line 30:         </td>
Line 31:         

有人可以帮我解决这个问题吗?

最佳答案

简单来说,您无法对可枚举对象建立索引。它的设计目的是一次按顺序吐出一个项目,而不是从堆栈中的任何位置吐出特定项目。最简单的解决方案是将其转换为 List:

@{
    var tblTestList = Model.ToList();
    for (var i = 0; i < tblTestList.Count(); i+=2 )
    {
        <tr>
            <td>
                @tblTestList[i].testId
            </td>
        </tr>
    }
}

或者更简单:

@model List<MvcApplication1.tblTest>

关于asp.net-mvc - 如何将索引应用于 IEnumerable 表达式类型并在 razor View 中并排显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22313842/

相关文章:

asp.net-mvc-3 - 如何对部分 View 进行批量持久化?

mysql - 删除 MySQL 表是否也会自动删除该表的索引?

jquery - CSS 文件中的硬编码 URL

c# - 为什么数据存储库不是静态的?

确认消息框中的 ASP.NET MVC ViewBag

sql-server - sql server 多列索引查询

python - 为什么我们在 Numpy 中进行双 bool 索引会得到这样的结果?

asp.net-mvc - 将 MVC3 添加到现有 Webform 解决方案

c# - 在 C# ASP.net 中链接多个数组的最佳方法

asp.net-mvc - 在 MVC3 razor 表单中使用多个局部 View