如何通过使用Asp.Net MVC Razor语法循环连续显示3个项目

时间:2014-03-11 23:48:27

标签: css asp.net-mvc razor

enter image description here 我遇到了一个我希望连续显示3个项目的场景。我成功地连续显示了2个项目。我试过了,但连续不能显示3个项目。在这方面的任何帮助将不胜感激。

以下是我试过的代码段

    @model  IList<MvcApplication1.tblTest>
   @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
    }

    <h2>Displaying three items(products) in a row</h2>

    <div style="display: inline-block">

    @for (var i = 0; i < Model.Count(); i++)
    {

        <div style="display: inline-block">

            <div> @Model[i].testId</div>
            <div>@Model[i].testName</div>      
            <div>@Model[i].testDescription</div> 

        </div>   

        if (i% 3 == 1)
        {
        <br />
        }
    }
</div>

3 个答案:

答案 0 :(得分:3)

尝试i%3 == 2

@model  IList<MvcApplication1.tblTest>
   @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
    }

    <h2>Displaying three items(products) in a row</h2>

    <div style="display: inline-block">

    @for (var i = 0; i < Model.Count(); i++)
    {

        <div style="display: inline-block">

            <div> @Model[i].testId</div>
            <div>@Model[i].testName</div>      
            <div>@Model[i].testDescription</div> 

        </div>   

        if (i% 3 == 2)
        {
        <br />
        }
    }
</div>

答案 1 :(得分:2)

当然,添加休息是一种方法,

但您可以考虑采用这种方法来避免添加//I have used bootstrap classed to style, you can have your own styling on this structure. @model IList<MvcApplication1.tblTest> @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Displaying three items(products) in a row</h2> <div style="display: inline-block"> @for (int i = 0; i < Model.Count(); i += 3) { <div class="row"> @{ int j = 0; for (; j <= 2 && i + j < Model.Count(); j++) { <div class="col-md-4"> <div> @Model[i + j].testId</div> <div>@Model[i + j].testName</div> <div>@Model[i + j].testDescription</div> </div> } } </div> } </div> 代码

在两个循环中迭代列表,一个循环以3为增量递增到最后一个元素,另一个从0到2递增。为外循环的每次迭代和内循环值添加div包装器。这样,您就可以在视图中获得更加结构化的HTML。

<?php
$response = array();
require 'db.php';

 $query = "SELECT * FROM news order by id desc";


    $result = mysqli_query($conn,$query);

    if (mysqli_num_rows($result) > 0) {

    $response["news"] = array();

    while ($row = $result->fetch_assoc()) {

            $arr[]=array('StudentId'=>$row["id"],'title'=>$row["title"],'description'=>$row["description"])
          }
           $response =$arr ;

    // echoing JSON response
    echo json_encode($response);
} else {

    $response = array('success'=>0);
    echo json_encode($response);
}

答案 2 :(得分:0)

它真的有效。感谢那。   

        @foreach (var item in WebApplication1.LanguageMang.AvailableLanguages)
        {
            <div style="display: inline-block"> <div>@Html.ActionLink(item.LanguageFullName, "ChangeLanguage", "Home", new { lang = item.LanguageCultureName }, new { @class = item.imgUrl })</div>
            </div>
        }

    </div>

enter image description here