ASP.NET Core 6中如何动态添加表格列?每行最多4列
实现每行最多4列的动态产品表格
核心思路
遍历从SQL Server获取的Product数据集,每4个产品生成一行表格,每行包含4个列;若产品总数不是4的倍数,最后一行可留空列保持表格结构,或直接显示剩余产品。
Product模型类(参考)
public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public string Description { get; set; } }
后端绑定数据的HTML实现(Razor示例)
假设已通过后端将Product列表传递到视图(如存入ViewBag.Products),直接用Razor语法循环渲染:
<table class="product-table"> <tbody> @{ var products = ViewBag.Products as List<Product>; int totalItems = products?.Count ?? 0; int rowCount = (int)Math.Ceiling(totalItems / 4.0); for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { <tr> @for (int colIndex = 0; colIndex < 4; colIndex++) { int productIndex = rowIndex * 4 + colIndex; <td> @if (productIndex < totalItems) { var product = products[productIndex]; <div class="product-card"> <h4>@product.Name</h4> <p>价格: @product.Price.ToString("C")</p> <p>@product.Description</p> </div> } </td> } </tr> } } </tbody> </table>
前端API获取数据的HTML实现(纯JS示例)
如果是前端通过API拉取产品数据,用JavaScript动态生成表格:
<table class="product-table" id="productTable"> <tbody></tbody> </table> <script> // 替换为实际API请求逻辑 async function loadProducts() { const response = await fetch('/api/products'); const products = await response.json(); const tbody = document.querySelector('#productTable tbody'); const rowCount = Math.ceil(products.length / 4); for (let row = 0; row < rowCount; row++) { const tr = document.createElement('tr'); for (let col = 0; col < 4; col++) { const itemIndex = row * 4 + col; const td = document.createElement('td'); if (itemIndex < products.length) { const item = products[itemIndex]; td.innerHTML = ` <div class="product-card"> <h4>${item.name}</h4> <p>价格: $${item.price.toFixed(2)}</p> <p>${item.description}</p> </div> `; } tr.appendChild(td); } tbody.appendChild(tr); } } // 页面加载时执行 window.onload = loadProducts; </script>
配套样式建议
.product-table { width: 100%; border-collapse: separate; border-spacing: 10px; margin: 20px 0; } .product-table td { width: 25%; padding: 12px; border: 1px solid #ddd; border-radius: 4px; vertical-align: top; } .product-card { text-align: center; } .product-card h4 { margin: 0 0 8px; color: #2d3748; }
内容的提问来源于stack exchange,提问作者Gojko Grubisic
相关产品推荐
相关产品推荐

