【问题标题】:How to use use enum Name inside of toList foreach?如何在 toList foreach 中使用枚举名称?
【发布时间】:2013-10-15 23:29:30
【问题描述】:

目前我在视图中显示枚举名称值,如下所示:

@foreach (var item in Model.DrawDatesList)
{
    <tr id="tableHeadRows">
        <td class="tableHeadRowsInside">
            @Html.DisplayFor(modelItem => item.LotteryId)
        </td>
        <td class="tableHeadRowsInside">
            @Enum.GetName(typeof(MediaBug.Shared.Enumerators.Days), item.DayId)
        </td>

...

一切正常。

但这是在foreach pagedList中使用的。 我在这样的操作中检索它:

    var results = ClientRepositoryBuilder
                    .Instance
                    .LotteryClientRepository
                    .GetAllDrawDates()
                    .ToPagedList(page, this.pageSize);
    var model = new LotteryIndexViewModel();
    model.DrawDatesList = results;

    return this.PartialView(model);

是否有任何选项我不在视图中使用 @Enum.GetName(typeof(MediaBug.Shared.Enumerators.Days), item.DayId) 并以某种方式在模型中分配它?但我不知道怎么做,因为你必须在 foreach 中使用它,你不能将它“插入”到 ToList 中。

【问题讨论】:

  • 什么是item.DayId

标签: c# asp.net-mvc enums


【解决方案1】:

DrawDatesList 是什么类型的对象?假设它是 IEnumerable。然后 DrawDate 可能看起来像这样:

public class DrawDate {
    public int DayId { get; set; }
    public int LotteryId { get; set; }
    public string DayName { get { return Enum.GetName(typeof(MediaBug.Shared.Enumerators.Days), DayId); } }
    // other properties here if applicable
}

或者,您可以将上面的 DayName 替换为:

    public string DayName { get { return ((MediaBug.Shared.Enumerators.Days) DayId).ToString(); } }

(只是语义问题。)

在你看来:

@foreach (var item in Model.DrawDatesList)
{
    <tr id="tableHeadRows">
        <td class="tableHeadRowsInside">
            @Html.DisplayFor(modelItem => item.LotteryId)
        </td>
        <td class="tableHeadRowsInside">
            item.DayName
        </td>

【讨论】:

  • 是的,但是您如何实际使用 ToList 中的 DayId 来获取正确的 DayId,在哪里通过 ToList 分配值?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
相关资源
最近更新 更多