如何在表格行中根据服务完成日期状态显示统一判断文本?
租赁系统物品服务状态显示问题
我开发了一个简易租赁系统,在租赁物业的详情页中有两个表格,分别用于展示租户和可维修物品。物品表格里的「Service in Progress」列需要实现这样的逻辑:遍历某一物品的所有Service记录,若任意一条服务的CompletionServiceDate为null,则显示“Yes”;若所有服务的CompletionServiceDate均有值,则显示“No”。
我当前用foreach循环遍历服务记录时遇到了问题:如果第一条服务已完成(有日期值)、另一条未完成,表格会为每个判断结果生成一列,但我只需要一列显示统一结果。现有的逻辑要么在第一条服务为null时显示“Yes”并跳出循环,要么第一条有值就显示“No”继续循环,无法实现“所有服务都完成才显示No”的需求。
相关模型代码
Rentals模型
public List<Tenant> Tenants { get; set; } public List<Item> Items { get; set; } public List<ItemType> ItemType { get; set; }
Item模型
public byte Active { get; set; } = 1; public ItemType ItemType { get; set; } [Display(Name = "Purchase Price")] [DisplayFormat(DataFormatString ="{0:C}")] public decimal PurchasePrice { get; set; } public List<Service> Services { get; set; }
Service模型
[Column(TypeName ="date")] [Display(Name = "Completion Service Date")] [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] public DateTime? CompletionServiceDate { get; set; }
当前视图代码
<table class="table table-bordered table-hover"> <thead> <tr> <th>Item Type</th> <th>Update</th> <th>Purchase Price</th> <th>Service in Progress</th> </tr> </thead> <tbody> @if (Model.Items.Count > 0 || Model.Items != null) { foreach (var item in Model.Items) { if (item.Active == 1) { <tr> <td>@Html.ActionLink(item.ItemType.Name, "Details", "Items", new { id = item.Id }, null)</td> <td> @Html.ActionLink("Move Item", "MoveItem", "Items", new { id = item.Id }, null) | @Html.ActionLink("New Service", "New", "Services", new { id = item.Id }, null) | @Html.ActionLink("Sell/Junk Item", "Update", "Items", new { id = item.Id }, null) </td> <td>$@item.PurchasePrice</td> @if (item.Services.Count > 0) { foreach (var service in item.Services) { if (service.CompletionServiceDate == null) { <td>Yes</td> break; } else { <td>No</td> } } } else { <td>No Services</td> } </tr> } } } </tbody> </table>
尝试过的另一种视图写法
@if (item.Services.Count > 0) { bool v = false; foreach (var service in item.Services) { if (service.CompletionServiceDate == null) { <td>Yes</td> break; } else { v = true; } } if (v ==true ) { <td>No</td> } } else { <td>No Services</td> }
解决方案
不用foreach循环逐个判断,直接用LINQ的Any方法可以简洁实现需求,而且不会生成多余的列:
替换视图中「Service in Progress」列的判断代码为:
<td> @if (item.Services.Count == 0) { @:No Services } else if (item.Services.Any(s => s.CompletionServiceDate == null)) { @:Yes } else { @:No } </td>
逻辑说明
item.Services.Any(s => s.CompletionServiceDate == null):只要有任意一条服务的CompletionServiceDate为null,就返回true,此时显示“Yes”- 如果所有服务的CompletionServiceDate都有值,
Any返回false,显示“No” - 没有服务记录时显示“No Services”
这样就能保证只生成一列,且判断逻辑完全符合需求。
内容的提问来源于stack exchange,提问作者Kennedy
相关产品推荐
相关产品推荐

