c#html循环,c# 如何在.NET Core Razor页面中使用foreach循环对表数据进行分组? - 糯米PHP...

我目前在练习15.2的第15章中,我们的任务是创建一个Razor页面,该页面生成按国家/地区分组的客户列表。当您单击客户名称时,它将带您到一个新页面,该页面显示该客户的完整联系方式及其订单列表。

Taking baby steps, I have built a page that has a card that will have the header as the country and then list each customer name on the card. However, my foreach loop is spitting out each data column under Customer.Country. So if there are 11 countries with Germany, it makes 11 cards with Germany as the title (see image).

It is also populating all of the customer's names as well under each country.

I found that I can use GroupBy() but as I explain below, that causes an invalid cast exception.

customers.cshtml

@page

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@using NorthwindEntitiesLib

@model NorthwindWeb.Pages.CustomersModel

Customers

@foreach (Customer customer in Model.Customers)

{

@customer.Country

@foreach (var name in Model.Customers)

{

@name.ContactName

}

}

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 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 Orders { get; set; }

}

}

I have tried using GroupBy to group the Countries and then populate the list but it gives an error for an invalid casting of type string.

@foreach (Customer customer in Model.Customers.GroupBy(c =>c.Country))

{

@customer.Country

@foreach (var name in Model.Customers)

{

@name.ContactName

}

}

InvalidCastException:无法将类型为“ System.Linq.Grouping`2 [System.String,NorthwindEntitiesLib.Customer]”的对象强制转换为“ NorthwindEntitiesLib.Customer”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值