如何在ASP.NET Core MVC中创建嵌套GridView
在ASP.NET Core MVC中实现嵌套GridView
ASP.NET Core MVC没有原生的GridView控件,我们可以通过Razor语法结合HTML表格,实现类似旧版ASP.NET 2.0嵌套GridView的效果,具体步骤如下:
1. 定义实体模型
创建主实体和关联的子实体,确保主实体包含子实体的集合属性:
// 主实体:分类 public class Category { public int Id { get; set; } public string Name { get; set; } public List<Product> Products { get; set; } } // 子实体:产品 public class Product { public int Id { get; set; } public string ProductName { get; set; } public decimal Price { get; set; } }
2. 控制器准备数据
在控制器中构造包含子数据的主实体列表,传递给视图:
public class HomeController : Controller { public IActionResult Index() { // 模拟从数据库获取的分类及产品数据 var categoryList = new List<Category> { new Category { Id = 1, Name = "电子产品", Products = new List<Product> { new Product { Id = 101, ProductName = "智能手机", Price = 3999 }, new Product { Id = 102, ProductName = "平板电脑", Price = 2999 } } }, new Category { Id = 2, Name = "家用电器", Products = new List<Product> { new Product { Id = 201, ProductName = "多门冰箱", Price = 5999 }, new Product { Id = 202, ProductName = "滚筒洗衣机", Price = 3499 } } } }; return View(categoryList); } }
3. 编写视图实现嵌套表格
通过两层Razor循环渲染主表格和嵌套的子表格,结合Bootstrap折叠组件实现展开/收起交互(需提前引入Bootstrap样式和脚本):
@model List<Category> <!-- 主表格 --> <table class="table table-bordered"> <thead> <tr> <th>分类ID</th> <th>分类名称</th> <th>操作</th> </tr> </thead> <tbody> @foreach (var category in Model) { <tr> <td>@category.Id</td> <td>@category.Name</td> <td> <!-- 展开/收起按钮 --> <button class="btn btn-sm btn-primary" data-bs-toggle="collapse" data-bs-target="#products-@category.Id"> 查看产品 </button> </td> </tr> <!-- 嵌套的子表格 --> <tr> <td colspan="3"> <div id="products-@category.Id" class="collapse"> <table class="table table-sm table-striped mt-2"> <thead> <tr> <th>产品ID</th> <th>产品名称</th> <th>价格</th> </tr> </thead> <tbody> @foreach (var product in category.Products) { <tr> <td>@product.Id</td> <td>@product.ProductName</td> <td>@product.Price.ToString("C")</td> </tr> } </tbody> </table> </div> </td> </tr> } </tbody> </table>
关键说明
- 核心逻辑是通过Razor的
foreach循环实现两层表格嵌套,外层遍历主数据,内层遍历关联的子数据 - 使用Bootstrap的折叠组件可以实现类似旧版GridView的展开/收起效果,提升交互体验
- 如果需要从数据库异步加载子数据,可以通过AJAX请求替换静态嵌套内容,实现更高效的数据加载
内容的提问来源于stack exchange,提问作者Makrokode
相关产品推荐
相关产品推荐

