首页 > 解决方案 > C# 语言命令的 Razor 语法

问题描述

我试图在引导网格的每一行上显示 4 个产品。

View此代码在除一行代码 ( @i = i-1;)之外按预期运行。

@for (int i = 0; i <= Model.Count() - 1; i++)
{
    <div class="row">
        @for (int j = 0; j < 4; j++)
        {
            if (i <= Model.Count() - 1)
            { 
            <div class="col-md-4">
                <h2>@Model[i].ItemName</h2>
                <br />
                <button style="border:none; padding:0;" OnClick="window.location.href='@Url.Action("Details", "Products", new { id = Model[i].ItemID })'"><img src="@Model[i].imageUrl",  width="100" height="75" /></button><br /><br />
                <p>
                    Price: @Model[i].ItemPrice
                    Availability:<span style="color:green; font-weight:bold;">Yes</span><br />
                </p>
                <p>
                    <button class="btn btn-default" OnClick="window.location.href='@Url.Action("Details", "Products", new { id = Model[i].ItemID })'">Learn more &raquo;</button>
                    <span style="margin-left:140px">@Html.ActionLink("Buy >>", "Index", "ShoppingCart", new { area = "" }, new { @class = "btn btn-primary btn-lg" })</span>
                </p>
            </div>

                i++;
            }
            else
            {
                return;
            }
        }
        @i = i-1;
    </div>
}

有人可以指导吗?

谢谢。

标签: c#asp.net-mvcrazor

解决方案


使用此代码在引导网格中的每一行显示 4 个产品

   @{
  int index = 0;
 }
 @foreach (var item in @Model)
 {
   if (index % 4 == 0)
   {
      @:  <div class="row">
   }

   <div class="col-md-3">

     <h2>@item.ItemName</h2>
            <br />
            <button style="border:none; padding:0;" OnClick="window.location.href='@Url.Action("Details", "Products", new { id = item.ItemID })'"><img src="@item.imageUrl",  width="100" height="75" /></button><br /><br />
            <p>
                Price: @item.ItemPrice
                Availability:<span style="color:green; font-weight:bold;">Yes</span><br />
            </p>
            <p>
                <button class="btn btn-default" OnClick="window.location.href='@Url.Action("Details", "Products", new { id = item.ItemID })'">Learn more &raquo;</button>
                <span style="margin-left:140px">@Html.ActionLink("Buy >>", "Index", "ShoppingCart", new { area = "" }, new { @class = "btn btn-primary btn-lg" })</span>
            </p>
   </div>

   if (index % 4 == 0)
   {
      @:     </div>
   }        

   index++;
}

推荐阅读