Shield UI Grid ASP.NET Core MVC结合EF Core操作SQL Server示例求助
使用Shield UI Grid + ASP.NET Core MVC + EF Core实现SQL Server数据增改查
嘿,我来帮你搞定这个需求!结合Shield UI Grid、ASP.NET Core MVC和EF Core实现SQL Server的数据读写与编辑,流程其实很清晰,我给你一步步拆解,附上可直接参考的示例代码~
1. 先确认基础准备(你应该已经完成的部分)
假设你已经有了EF Core的DbContext和对应的实体类,这里我用Product实体做示例,你可以替换成自己的业务实体:
// 实体类示例 public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public int Stock { get; set; } } // DbContext示例 public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } }
同时确保你已经在Program.cs里配置好SQL Server连接字符串和EF Core服务(这部分就不重复啦)。
2. 后端控制器:数据获取+更新接口
控制器需要两个核心方法:一个返回带Grid的视图并传递数据,另一个接收Grid提交的修改数据,用EF Core同步到数据库。
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; public class ProductsController : Controller { private readonly AppDbContext _context; public ProductsController(AppDbContext context) { _context = context; } // 渲染带Shield UI Grid的视图 public async Task<IActionResult> Index() { // 从SQL Server取数据,转成IEnumerable传给视图 var products = await _context.Products.ToListAsync(); return View(products); } // 接收Grid的修改数据并更新数据库 [HttpPost] public async Task<IActionResult> UpdateProducts([FromBody] List<Product> updatedProducts) { if (updatedProducts == null || !updatedProducts.Any()) { return BadRequest("没有收到需要更新的数据"); } foreach (var updatedProduct in updatedProducts) { // 找到数据库中对应的实体 var existingProduct = await _context.Products.FindAsync(updatedProduct.Id); if (existingProduct != null) { // 按需更新字段,这里根据你的实体调整 existingProduct.Name = updatedProduct.Name; existingProduct.Price = updatedProduct.Price; existingProduct.Stock = updatedProduct.Stock; // 标记实体为修改状态 _context.Entry(existingProduct).State = EntityState.Modified; } // 如果是新增数据(比如ID为0的情况),可以在这里添加: // else if (updatedProduct.Id == 0) // { // _context.Products.Add(updatedProduct); // } } try { await _context.SaveChangesAsync(); return Ok(new { success = true, message = "数据更新成功" }); } catch (Exception ex) { return StatusCode(500, $"更新失败:{ex.Message}"); } } }
3. 前端视图:配置可编辑的Shield UI Grid
在Index.cshtml里配置Grid的编辑功能,加上保存按钮把修改数据提交到后端:
@model IEnumerable<Product> @{ ViewData["Title"] = "产品管理"; } <h1>产品管理</h1> <!-- Shield UI Grid容器 --> <div id="productsGrid"></div> <!-- 保存修改按钮 --> <button id="saveChangesBtn" class="btn btn-primary mt-3">保存修改</button> @section Scripts { <script type="text/javascript"> $(document).ready(function () { // 初始化Shield UI Grid $("#productsGrid").shieldGrid({ dataSource: { data: @Html.Raw(Json.Serialize(Model)), // 把后端数据序列化为JSON传给Grid schema: { fields: { Id: { type: "number" }, Name: { type: "string" }, Price: { type: "number" }, Stock: { type: "number" } } } }, columns: [ { field: "Id", title: "ID", width: "80px", editable: false }, // ID设为不可编辑 { field: "Name", title: "产品名称", width: "200px", editable: true }, { field: "Price", title: "价格", width: "120px", editable: true, format: "{0:C}" }, { field: "Stock", title: "库存", width: "100px", editable: true } ], editing: { enabled: true, // 开启编辑功能 type: "cell" // 单元格编辑模式,也可换成row(整行编辑)或popup(弹窗编辑) }, toolbar: [ { buttons: [ { commandName: "insert", caption: "添加产品" }, { commandName: "delete", caption: "删除选中" } ] } ], events: { // 处理新增行的默认值逻辑(可选) insert: function (e) { e.dataItem.Id = 0; // 用0标记为新增数据,后端识别后执行添加操作 } } }); // 保存按钮点击事件 $("#saveChangesBtn").click(function () { var grid = $("#productsGrid").swidget(); // 获取Grid中所有修改/新增/删除的数据 var changedData = grid.dataSource.changes(); if (changedData.length === 0) { alert("没有需要保存的修改"); return; } // 提交数据到后端接口 $.ajax({ url: "@Url.Action("UpdateProducts", "Products")", type: "POST", contentType: "application/json", data: JSON.stringify(changedData), success: function (response) { alert(response.message); // 提交后清除Grid的修改状态,也可以重新加载数据 grid.dataSource.commitChanges(); }, error: function (xhr) { alert("保存失败:" + xhr.responseText); } }); }); }); </script> }
4. 关键细节提示
- 编辑模式切换:示例用的是
cell单元格编辑,你可以把editing.type改成row或popup来切换编辑方式。 - 删除功能:如果要实现删除,需要在后端额外写一个删除接口,或者在
UpdateProducts里识别删除的行(比如Grid会标记_destroy属性),执行_context.Products.Remove(existingProduct)。 - 数据验证:前端可以在Grid的字段配置里加验证规则,后端也要添加模型验证(比如给实体类加
[Required]等特性),避免非法数据入库。
内容的提问来源于stack exchange,提问作者Mo Ibrahim
相关产品推荐
相关产品推荐

