【问题标题】:Use Html.DisplayNameFor with IEnumerable<IGrouping>将 Html.DisplayNameFor 与 IEnumerable<IGrouping> 一起使用
【发布时间】:2019-06-25 18:47:34
【问题描述】:

我从显示值表 (IEnumerable&lt;FooViewModel&gt;) 切换到在 Razor 页面中显示分组值表 (IEnumerable&lt;IGrouping&lt;DateTime, FooViewModel&gt;&gt;)。

获取模型属性的显示名称的语法是@Html.DisplayNameFor(model =&gt; model.ID)

我认为 DisplayNameForIGrouping&lt;DateTime, FooViewModel&gt; 使用的语法不正确,因为它只显示模型的一个属性(在本例中为 ID):@Html.DisplayNameFor(item =&gt; item.FirstOrDefault().ElementAtOrDefault(0).ID)

正确的语法是什么?

【问题讨论】:

  • 如何使用FirstOrDefaultElementAtOrDefaultDisplayNameFor 不是总是只显示一个属性的 DisplayName 吗?你希望它做什么?
  • 您的问题不清楚。 “它只显示模型的一个属性” - 是的,这就是它的作用。您不能在模型级别使用DisplayNameFor 以某种方式呈现所有属性的名称。这不是它的工作原理。
  • 我犯了一个错误——语法是正确的。投票关闭。呃。

标签: c# linq razor asp.net-core-mvc


【解决方案1】:

我认为你的语法是正确的!

@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 }
};

应该是这样的:

【讨论】:

  • FooViewModel 具有未显示的其他属性(例如 NameStartingDate)。
  • @craig:你不能只添加更多带有&lt;th&gt;@Html.DisplayNameFor(model =&gt; model.First().ElementAt(0).Name)&lt;/th&gt;&lt;th&gt;@Html.DisplayNameFor(model =&gt; model.First().ElementAt(0).StartingDate)&lt;/th&gt;等标题的列吗?就像@Chris Pratt 所说的那样,你的问题还不清楚,所以我猜到了你在寻找什么。
猜你喜欢
  • 2013-02-02
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-30
  • 2022-12-18
相关资源
最近更新 更多