簡體   English   中英

將Html.DisplayNameFor與IEnumerable一起使用<IGrouping>

[英]Use Html.DisplayNameFor with IEnumerable<IGrouping>

我從顯示值表( IEnumerable<FooViewModel> )切換為在Razor頁面中顯示分組的值表( IEnumerable<IGrouping<DateTime, FooViewModel>> )。

獲取模型屬性的顯示名稱的語法為@Html.DisplayNameFor(model => model.ID)

我認為我沒有將DisplayNameForIGrouping<DateTime, FooViewModel>一起使用的正確語法,因為它僅顯示模型的屬性之一(在本例中為ID ): @Html.DisplayNameFor(item => item.FirstOrDefault().ElementAtOrDefault(0).ID)

正確的語法是什么?

我認為您的語法正確!

@model IEnumerable<IGrouping<DateTime, FooViewModel>>

@if (Model.Any())
{
    /*
     * Since we've checked there are groupings, you can just use .First() to get 
     * the first group.
     *
     * .Key will give you the key you use to group things by. In this case, it's 
     * DateTime.
     *
     * Since there are groupings, there must be elements in the group so it's safe 
     * to use .ElementAt() to get to the view model, FooViewModel.
     */

    <table class="table">
        <thead>
            <tr>
                <th>@Html.DisplayNameFor(model => model.First().Key)</th>
                <th>@Html.DisplayNameFor(model => model.First().ElementAt(0).ID)</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var group in Model)
            {
                <tr>
                    <td>@group.Key</td>
                    <td>@String.Join(", ", group.Select(x => x.ID))</td>
                </tr>
            }
        </tbody>
    </table>
}

並帶有假數據:

public class FooViewModel
{
    [Display(Name = "Date time")]
    public DateTime DateTime { get; set; }

    [Display(Name = "Haha ID")]
    public int ID { get; set; }
}

var data = new List<FooViewModel>
{
    new FooViewModel { DateTime = new DateTime(2019, 06, 25), ID = 1 },
    new FooViewModel { DateTime = new DateTime(2019, 06, 25), ID = 2 },
    new FooViewModel { DateTime = new DateTime(2019, 06, 24), ID = 3 },
    new FooViewModel { DateTime = new DateTime(2019, 06, 23), ID = 4 }
};

它應該看起來像:

在此處輸入圖片說明

暫無
暫無

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

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