如何在C# Core中遍历VM格式返回的数据?
解决遍历C#服务返回数据生成PDF HTML的问题
根据你提供的代码和数据结构信息,rv是ServiceResponse<AccountInvoiceResponse>类型的对象,真正的发票数据藏在rv.Result.AccountInvoices这个集合里,你可以按以下步骤遍历并生成HTML:
1. 正确获取发票集合
首先从返回结果中提取出要遍历的发票列表,注意加空值判断防止异常:
var invoices = new List<AccountInvoice>(); if (rv != null && rv.Result != null && rv.Result.AccountInvoices != null) { invoices = rv.Result.AccountInvoices; }
2. 生成PDF可用的HTML
方式一:控制器内拼接HTML字符串
如果需要在控制器里直接生成HTML,可以用StringBuilder来构建:
var htmlBuilder = new StringBuilder(); // 构建基础HTML结构和表格表头 htmlBuilder.Append(@" <!DOCTYPE html> <html> <head> <style> table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #000; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } </style> </head> <body> <h2>账户发票列表</h2> <table> <thead> <tr> <th>发票编号</th> <th>客户名称</th> <th>金额</th> <th>开票日期</th> </tr> </thead> <tbody>"); // 遍历发票生成表格行 foreach (var invoice in invoices) { htmlBuilder.AppendFormat(@" <tr> <td>{0}</td> <td>{1}</td> <td>{2:C}</td> <td>{3:yyyy-MM-dd}</td> </tr>", invoice.InvoiceNumber, // 替换为你实际的属性名 invoice.CustomerName, invoice.TotalAmount, invoice.InvoiceDate); } // 闭合HTML标签 htmlBuilder.Append(@" </tbody> </table> </body> </html>"); // 最终用于生成PDF的HTML字符串 var pdfHtml = htmlBuilder.ToString();
方式二:用Razor视图生成(更推荐)
如果是MVC项目,把发票列表传给Razor视图来生成HTML会更易维护:
// 控制器方法中传递数据到视图 return View(invoices);
然后在对应的Razor视图里编写遍历逻辑:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <style> table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #000; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } </style> </head> <body> <h2>账户发票列表</h2> <table> <thead> <tr> <th>发票编号</th> <th>客户名称</th> <th>金额</th> <th>开票日期</th> </tr> </thead> <tbody> @foreach (var invoice in Model) { <tr> <td>@invoice.InvoiceNumber</td> <td>@invoice.CustomerName</td> <td>@invoice.TotalAmount.ToString("C")</td> <td>@invoice.InvoiceDate.ToString("yyyy-MM-dd")</td> </tr> } </tbody> </table> </body> </html>
注意事项
- 替换代码中的属性名(比如
InvoiceNumber、CustomerName)为你实际的AccountInvoice类属性名称 - 生成HTML时加入基础样式,确保PDF渲染时格式正常
- 始终做好空值判断,避免空引用异常
内容的提问来源于stack exchange,提问作者saurav.rox
相关产品推荐
相关产品推荐

