html - 无法使用 Razor 在 foreach 中关闭标记 - ASP.NET MVC

标签 html asp.net-mvc razor

我有一个 div,每个 div 都有两个 div,如下所示:

<div class="col">
    <div class="item-c color1">..</div>
    <div class="item-c color2">..</div>
</div>

我从数据库中读取数据,我想用 foreach 语句重复这个 div。

我使用下面的代码,但出现了运行时错误

<div class="col">
@foreach (var item in Model)
{

    <div class="item-c  @("color" + index.ToString()) ">..</div>
    if (index % 2 == 0)
    {
        <text></div><div class="col"></text>
    }
    index++;
    if (index > 8) { index = 1; }
}

我的结果应该是这样的: enter image description here 我收到此错误:

Encountered end tag "div" with no matching start tag

最佳答案

你的代码需要

@{ int index = 1; }

<div class="col">
    @foreach(var item in Model.Items)
    {
        <div class="item-c color@(index)">..</div>
        if (index % 2 == 0) // close the div and start a new one
        {
            @:</div><div class="col">
        }
        index++;
        if (index > 8) { index = 1; }
    }
</div>

关于html - 无法使用 Razor 在 foreach 中关闭标记 - ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35540279/

相关文章:

jquery - 返回 HTML 时出现错误 : Syntax error, 无法识别的表达式

javascript - 如何使这个书架网格具有拖动/选择功能?

jquery - 在 AJAX 上更新模型时出现问题 "POST"

c# - double 值的 string.Format() 给出不准确的结果

HTML5 视频 - 暂停加载/部分加载

html - Bootstrap 类容器不起作用

php - 如何在 php foreach 循环中替换 div 元素

c# - 使用 AJAX 在 jquery 对话框内的 jquery 选项卡内加载 MVC 用户控件(C# Inside)

使用旧 css 的 HTML5 渲染

c# - foreach 中的 LabelFor()