如何在MVC C#中获取.include数据?

问题描述 投票:0回答:1

我有此操作方法,该方法将IQueryable返回到视图。

    public ActionResult Index()
    {
        var cafeTableDetails = db.CafeTableDetails.Include(c => c.CafeTable).Include(c => c.Food);

        return View(cafeTableDetails.ToList());
    }

在我看来,

@model IEnumerable<MVC_Cafe.Models.CafeTableDetails>

<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.CafeTable.TableNo)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Food.FoodName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Quantity)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.TotalAmount)
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CafeTable.TableNo)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Food.FoodName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Quantity)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TotalAmount)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.Id })
        </td>
    </tr>

}
<tr>
    <td colspan="5"></td>
</tr>
</table>

我可以显示视图,但现在我不知道如何显示最后一个tr标签中每个循环之后的总顺序。总数存储在CafeTable中。这是我的模特

public class CafeTable
{
    public int Id { get; set; }
    public string TableNo { get; set; }
    public TableStatus TableStatus { get; set; }
    public decimal TableAmount { get; set; }
    public int TotalOrders { get; set; }

    // Navigation Properties
    public ICollection<CafeTableDetails> CafeTableDetails { get; set; }
}

public enum TableStatus
{
    Empty, Occupied
}

public class CafeTableDetails
{
    public int Id { get; set; }
    public int CafeTableId { get; set; } // FK
    public int FoodId { get; set; } // FK
    public int Quantity { get; set; }
    public decimal TotalAmount { get; set; }

    // Navigation Properties
    public CafeTable CafeTable { get; set; }
    public Food Food { get; set; }
}

我可以在for每个循环的内部,但是不确定如何将其添加到outside for每个循环的内部

@Html.DisplayFor(modelItem => item.CafeTable.TableAmount)
c# asp.net-mvc linq view
1个回答
0
投票

您应该创建如下的CafeTableViewModel

public class CafeTableViewModel
{
    public int TotalOrders { get; set; }
    public List<CafeTableDetails> CafeTableDetails { get; set; }
}

Index操作中,您可以通过这种方式获得

public ActionResult Index()
{
    var cafeTableDetails = db.CafeTableDetails.Include(c => c.CafeTable).Include(c => c.Food);
    var totalOrders = cafeTableDetails.Sum(p => p.TotalAmount);
    var viewModel = new CafeTableViewModel 
                    { TotalOrders = totalOrders, CafeTableDetails = cafeTableDetails.ToList()}
    return View(viewModel);
}
© www.soinside.com 2019 - 2024. All rights reserved.