簡體   English   中英

C#MVC3 Razor在@foreach列表中交替項目?

[英]C# MVC3 Razor alternating items in a @foreach list?

在MVC3中,如何在使用Razor視圖引擎時在@foreach列表上創建交替的行顏色?

@foreach (var item in Model) {    
    <tr>
        <td>@item.DisplayName</td>
        <td>@item.Currency</td>
        <td>@String.Format("{0:dd/MM/yyyy}", item.CreatedOn)</td>
        <td>@String.Format("{0:g}", item.CreatedBy)</td>
        <td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
    </tr>
}

假設您不想使用CSS(即:nth-child(odd) ),您可以:

  • 使用正常for循環:

     @for (int i = 0; i < Model.Count; i++) { ... } 
  • 使用.Select

     @foreach (var item in Model.Select((x, i) => new { Data = x, Index = i })) { ... } 

無論哪種方式,您都可以訪問當前索引,然后可以使用i % 2 == 1作為背景顏色的條件。 就像是:

<tr style="background-color:@(i % 2 == 1 ? "red" : "white")">...</tr>

這就是CSS的用途(改變風格而不是內容)。 節省服務器的努力:在客戶端上執行。

由於您使用的是Razor,因此可以使用JQuery。 以下是我在項目中的表現:

$(document).ready(function () {
    $("table > tbody tr:odd").css("background-color", "#F7F7F7");
}

使用ASP.NET MVC 3和新的@helper語法,有一種更簡潔的方法來處理它。

首先添加這個@helper方法:

@helper AlternateBackground(string color) {
    if (ViewBag.count == null) { ViewBag.count = 0; }
    <text>style="background-color:@(ViewBag.count % 2 == 1 ? color : "none")"</text>
    ViewBag.count++;
}

然后只需將調用添加到<TR>元素中的助手

@foreach (var item in Model) {    
    <tr @AlternateBackground("Red")>
        <td>@item.DisplayName</td>
        <td>@item.Currency</td>
        <td>@String.Format("{0:dd/MM/yyyy}", item.CreatedOn)</td>
        <td>@String.Format("{0:g}", item.CreatedBy)</td>
        <td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
    </tr>
}

您總是可以使用以下方法在純CSS中執行以下操作:

TABLE.test tr:nth-child(even)
{
    background-color: #EFEFEF;
}

這樣的事怎么樣?

@for (int i = 0; i < Model.length; i++) {
  <tr @(i % 2 != 0 ? class="odd" : "")>
    <td>@Model[i].DisplayName</td>
    <td>@Model[i].Currency</td>
    <td>@String.Format("{0:dd/MM/yyyy}", Model[i].CreatedOn)</td>
    <td>@String.Format("{0:g}", Model[i].CreatedBy)</td>
    <td>@Html.ActionLink("Edit", "Edit", new { id = Model[i].Id })</td>
  </tr>
@{  
    int i = 0;
    foreach (Account acct in Model)
    {
        <div class="row @(i%2==0?"even":"odd")">     
            <a href="/Account/Details/@acct.id">@acct.name</a>
        </div>
        i++;
    }
}

原文: http//15daysofjquery.com/table-striping-made-easy/5/作者:Jack Born jQuery Zebra_Striping_Made_Easy

=============== Java腳本===================

$(document).ready(function () {
          $('.stripeMe tr:even').addClass('alt');

          $('.stripeMe tr').hover(
            function () {
                $(this).addClass("highlight");
              },
             function () {
                $(this).removeClass("highlight");
              });
      });

================= css =================

tr.alt td {
background-color : #F7F7F7;
}
tr.highlight td {
background-color : #bcd4ec;
}

=============== HTML ===============

<table class="stripeMe">

關於它的文檔不多,但Loop Helper( http://nuget.org/Packages/Packages/Details/Loop-Helper-for-WebMatrix-0-1 )為您提供了檢測偶數/奇數/等的支持。 項目。

一個舊帖子,但沒有一個答案涵蓋了這種方法,所以我會。

由於您正在使用MVC Razor,因此使用@helper函數是最簡單,最干凈和最好的方法。

在項目的App_Code文件夾中,使用以下代碼添加新項或修改現有的CustomeHelpers.cshtml文件:

@helper AlternateBackground(string color, Int32 iViewBagCount) {
    if (iViewBagCount == null) { iViewBagCount = 0; }
    <text>style="background-color:@(iViewBagCount % 2 == 1 ? color : "none")"</text>
    iViewBagCount++;
}

然后在您的視圖中,您的foreach循環將如下所示:

@foreach (var item in Model) {    
    <tr @CustomHelpers.AlternateBackground("#ECEDEE", Model.Count())>
        <td>@item.DisplayName</td>
        <td>@item.Currency</td>
        <td>@String.Format("{0:dd/MM/yyyy}", item.CreatedOn)</td>
        <td>@String.Format("{0:g}", item.CreatedBy)</td>
        <td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
    </tr>
}

您可以傳遞顏色標識符,如“#ECEDEE”或命名顏色“藍色”。

這樣,您只需添加@Helper函數一次,它就會在整個應用程序中傳播,並且可以根據需要通過引用@CustomHelpers函數在每個視圖上調用它。

我用來支持IE8(企業瀏覽器,而不是選擇)的解決方案是將the_lotus的解決方案與jquery解決方案相結合

由於IE8不支持nth-child()使用此css

.tableclass tr.even{
    background:#E6EDF5;
}

並使用jQuery執行此操作:

$(document).ready(function() {
    $(".table tr:nth-child(even)").addClass("even");
});

可以讓框架決定如何最好地呈現它,可能使用一些瀏覽器檢測邏輯和其內置的任何其他優點,如下所示,並繼續您的生活。

:-)

我的觀點是,通過這種方法,WebGrid將使用最佳技術控制交替的網格顏色(至少它被設計為使用,至少)用於檢測到的瀏覽器。 它可能不會使用“第n”CSS語法,但無論如何,這可能不適用於所有目標受眾,因此您必須自己檢測瀏覽器並發出不同的內容。 當然,現在每個人都應該使用符合CSS 3.x標准的瀏覽器,但里程會有所不同。

@myWebGrid.GetHtml
    (
    tableStyle: "some-style",
    headerStyle: "some-head-style",
    alternatingRowStyle: "some-fancy-alt-row-style",
    etc ...
    )

System.Web.Helpers.WebGridGetHtml方法簽名如下所示:

public IHtmlString GetHtml
    (
    string tableStyle = null,
    string headerStyle = null,
    string footerStyle = null,
    string rowStyle = null,
    string alternatingRowStyle = null,
    string selectedRowStyle = null,
    string caption = null,
    bool displayHeader = true,
    bool fillEmptyRows = false,
    string emptyRowCellValue = null,
    IEnumerable<WebGridColumn> columns = null,
    IEnumerable<string> exclusions = null,
    WebGridPagerModes mode = WebGridPagerModes.Numeric | WebGridPagerModes.NextPrevious,
    string firstText = null,
    string previousText = null,
    string nextText = null,
    string lastText = null,
    int numericLinksCount = 5,
    object htmlAttributes = null
    );

你可以做的是在foreach()之外設置一個變量odd

@{
    var odd = false;
}

然后,在foreach循環中,您將更改它的值,然后在if條件中使用它來設置交替類。

@foreach (var item in Model) {
    odd = !odd;

    <tr class="@(odd ? "odd" : "even")">
        <td>@item.DisplayName</td>
        <td>@item.Currency</td>
        <td>@String.Format("{0:dd/MM/yyyy}", item.CreatedOn)</td>
        <td>@String.Format("{0:g}", item.CreatedBy)</td>
        <td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
    </tr>
}

@helper Prop(List prop){foreach(var p in prop){p}}

格式:@Prop(@ item.Prop)

那么使用jQuery DataTable插件呢。 我在我開發的MVC2應用程序上使用它。

http://www.datatables.net/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM