我是靠谱客的博主 标致短靴,最近开发中收集的这篇文章主要介绍c#html循环,c# 如何在.NET Core Razor页面中使用foreach循环对表数据进行分组? - 糯米PHP...Customers,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

我目前在练习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”。

最后

以上就是标致短靴为你收集整理的c#html循环,c# 如何在.NET Core Razor页面中使用foreach循环对表数据进行分组? - 糯米PHP...Customers的全部内容,希望文章能够帮你解决c#html循环,c# 如何在.NET Core Razor页面中使用foreach循环对表数据进行分组? - 糯米PHP...Customers所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部