【发布时间】:2020-05-06 18:45:44
【问题描述】:
我在本书中关注C# 8.0and .NET Core 3.0 - Modern Cross-Platform Development
我目前在第 15 章的练习 15.2 中,我们的任务是创建一个 Razor 页面,该页面生成按国家/地区分组的客户列表。当您单击客户名称时,它会将您带到一个新页面,其中显示该客户的完整联系方式和他们的订单列表。
迈出小步,我建立了一个页面,该页面有一张卡片,标题为国家/地区,然后列出卡片上的每个客户姓名。但是,我的 foreach 循环会吐出 Customer.Country 下的每个数据列。因此,如果有 11 个国家有德国,它会制作 11 张以德国为标题的卡片 (see image)。
它还会在每个国家/地区填充所有客户的姓名。
我发现我可以使用 GroupBy() 但正如我在下面解释的那样,这会导致无效的强制转换异常。
customers.cshtml
@page
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using NorthwindEntitiesLib
@model NorthwindWeb.Pages.CustomersModel
<div class="row">
<h1 class="display2">Customers</h1>
</div>
<div class="row">
@foreach (Customer customer in Model.Customers)
{
<div class="card border-info mb-3" style="max-width: 18rem">
<div class="card-header text-white bg-info">
@customer.Country
</div>
<ul class="list-group list-group-flush">
@foreach (var name in Model.Customers)
{
<li class="list-group-item">@name.ContactName</li>
}
</ul>
</div>
}
</div>
customers.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using NorthwindContextLib;
using NorthwindEntitiesLib;
namespace NorthwindWeb.Pages
{
public class CustomersModel : PageModel
{
private Northwind db;
public CustomersModel(Northwind injectedContext)
{
db = injectedContext;
}
public IEnumerable<Customer> Customers { get; set; }
public void OnGet()
{
Customers = db.Customers
.ToArray();
}
}
}
NorthwindEntitesLib
namespace NorthwindEntitiesLib
{
public class Customer
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public ICollection<Order> Orders { get; set; }
}
}
我尝试使用 GroupBy 对国家/地区进行分组,然后填充列表,但它给出了类型字符串类型转换无效的错误。
@foreach (Customer customer in Model.Customers.GroupBy(c =>c.Country))
{
<div class="card border-info mb-3" style="max-width: 18rem">
<div class="card-header text-white bg-info">
@customer.Country
</div>
<ul class="list-group list-group-flush">
@foreach (var name in Model.Customers)
{
<li class="list-group-item">@name.ContactName</li>
}
</ul>
</div>
}
InvalidCastException:无法将“System.Linq.Grouping`2[System.String,NorthwindEntitiesLib.Customer]”类型的对象转换为“NorthwindEntitiesLib.Customer”类型。
【问题讨论】:
-
添加 Model.Customers.GroupBy(c =>c.Country).ToList() 看看是否有帮助
-
抛出与上面相同的 InvalidCastException。
-
我正在为您解答。一秒
-
我发现 Model.Customers.GroupBy(c=>c.Country) .Select(c => c.First()) 产生了我想要的结果分组。现在我需要弄清楚如何仅将那些居住在该国家/地区的客户纳入其预期国家/地区。
标签: c# asp.net-mvc asp.net-core razor-pages