You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Tabulator的AJAX HTTP Post提交修改后的数据至DWH表?

实现Tabulator修改数据的HTTP POST提交到SQL Server表

我完全懂你现在的困扰——用Tabulator把数据仓库视图的内容展示出来已经搞定了,但要把修改后的数据提交回dbo.BEDS表就摸不着头绪了,尤其是Tabulator结合AJAX做POST提交这块,相关示例确实不多,新手踩坑很正常。我来一步步帮你把整个流程打通,从后端的API接口到前端的Tabulator配置都给你写明白,直接就能用的那种。

1. 先确认你的Bed数据模型

首先要确保你的实体模型和dbo.BEDS表字段完全对应,比如:

public class Bed
{
    public int BedId { get; set; } // 主键,和表中BedId字段对应
    public string BedNumber { get; set; }
    public string Status { get; set; }
    public DateTime LastUpdated { get; set; }
    // 其他和dbo.BEDS表匹配的字段,比如病房号、备注等
}

2. 数据库上下文(DbContext)配置

确保你的DbContext里已经注册了BEDS表的DbSet,这样EF Core才能操作这个表:

using Microsoft.EntityFrameworkCore;

public class HospitalDbContext : DbContext
{
    public HospitalDbContext(DbContextOptions<HospitalDbContext> options) : base(options)
    {
    }

    // 对应dbo.BEDS表
    public DbSet<Bed> BEDS { get; set; }
}

3. 后端API Controller实现POST接口

我给你写一个支持批量提交的接口(Tabulator可以批量收集修改数据,比单条提交更高效),同时也兼容单条数据提交:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using YourNamespace.Models;

[Route("api/[controller]")]
[ApiController]
public class BedsController : ControllerBase
{
    private readonly HospitalDbContext _context;

    public BedsController(HospitalDbContext context)
    {
        _context = context;
    }

    // 批量更新Bed数据的POST接口
    [HttpPost("UpdateBeds")]
    public async Task<IActionResult> UpdateBeds([FromBody] List<Bed> updatedBeds)
    {
        // 校验传入数据
        if (updatedBeds == null || !updatedBeds.Any())
        {
            return BadRequest("没有接收到需要更新的数据");
        }

        try
        {
            foreach (var bed in updatedBeds)
            {
                var existingBed = await _context.BEDS.FindAsync(bed.BedId);
                if (existingBed != null)
                {
                    // 更新允许修改的字段,根据你的业务需求调整
                    existingBed.BedNumber = bed.BedNumber;
                    existingBed.Status = bed.Status;
                    existingBed.LastUpdated = DateTime.Now;
                    // 其他需要更新的字段...
                }
                else
                {
                    // 如果需要支持新增Bed,可以在这里添加逻辑
                    _context.BEDS.Add(bed);
                }
            }

            await _context.SaveChangesAsync();
            return Ok("病床数据更新成功");
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"更新数据失败:{ex.Message}");
        }
    }
}

4. 前端Tabulator配置AJAX POST提交

这里给你两种常用的提交方式,根据你的业务场景选就行:

方式一:单元格编辑完成后立即提交

适合实时保存单条修改的场景:

<div id="bed-table"></div>

<script>
    // 初始化Tabulator表格
    var bedTable = new Tabulator("#bed-table", {
        height: "500px",
        layout: "fitColumns",
        columns: [
            { title: "病床ID", field: "BedId", frozen: true, editable: false },
            { title: "病床编号", field: "BedNumber", editable: true },
            { 
                title: "状态", 
                field: "Status", 
                editable: true, 
                editor: "select", 
                editorParams: { values: ["空闲", "占用", "维护中"] } 
            },
            { title: "最后更新时间", field: "LastUpdated", formatter: "datetime", editable: false },
            // 其他列配置...
        ],
        // 加载初始数据的AJAX(你已经实现的部分)
        ajaxURL: "/api/Beds/GetBeds",
        ajaxConfig: "GET",
        // 单元格编辑完成后触发提交
        cellEdited: function(cell) {
            const rowData = cell.getRow().getData(); // 获取当前行的完整数据

            // 发送POST请求到后端接口
            fetch("/api/Beds/UpdateBeds", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify([rowData]), // 用数组包装,适配后端的List<Bed>参数
            })
            .then(response => {
                if (!response.ok) throw new Error("网络请求失败");
                return response.text();
            })
            .then(resMsg => {
                console.log("更新成功:", resMsg);
                // 实时更新当前行的最后修改时间
                cell.getRow().update({ LastUpdated: new Date().toISOString() });
            })
            .catch(err => {
                console.error("更新失败:", err);
                // 编辑失败时恢复单元格原始值
                cell.getRow().revert();
                alert("病床数据更新失败,请重试");
            });
        }
    });
</script>

方式二:批量提交所有修改

适合用户修改多行后统一保存的场景,需要开启Tabulator的历史跟踪:

<div id="bed-table"></div>
<button id="save-all-btn" style="margin-top:10px;">保存所有修改</button>

<script>
    var bedTable = new Tabulator("#bed-table", {
        height: "500px",
        layout: "fitColumns",
        columns: [
            // 和上面一致的列配置
            { title: "病床ID", field: "BedId", frozen: true, editable: false },
            { title: "病床编号", field: "BedNumber", editable: true },
            { 
                title: "状态", 
                field: "Status", 
                editable: true, 
                editor: "select", 
                editorParams: { values: ["空闲", "占用", "维护中"] } 
            },
            { title: "最后更新时间", field: "LastUpdated", formatter: "datetime", editable: false },
        ],
        ajaxURL: "/api/Beds/GetBeds",
        ajaxConfig: "GET",
        // 开启历史跟踪,才能获取修改过的数据
        history: true,
    });

    // 绑定保存按钮点击事件
    document.getElementById("save-all-btn").addEventListener("click", function() {
        const changedData = bedTable.getChangedData(); // 获取所有修改/新增/删除的行
        if (changedData.length === 0) {
            alert("没有需要保存的修改");
            return;
        }

        fetch("/api/Beds/UpdateBeds", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(changedData),
        })
        .then(response => {
            if (!response.ok) throw new Error("网络请求失败");
            return response.text();
        })
        .then(resMsg => {
            console.log("批量更新成功:", resMsg);
            bedTable.clearHistory(); // 清除历史修改记录
            alert("所有修改已保存");
            // 可选:刷新表格数据,确保显示最新状态
            bedTable.setData();
        })
        .catch(err => {
            console.error("批量更新失败:", err);
            alert("保存失败,请重试");
        });
    });
</script>

5. 几个关键注意事项

  • 跨域问题:如果前端页面和API不在同一域名下,需要在后端配置CORS(在Program.cs里添加CORS中间件)。
  • 数据验证:建议在Bed模型上添加[Required]、[MaxLength]等验证特性,Controller里通过ModelState.IsValid校验传入数据的合法性。
  • 主键匹配:提交的数据必须包含主键BedId,否则后端无法找到对应的记录进行更新。
  • 错误处理:前端一定要处理网络错误和后端返回的错误,给用户明确的提示,避免用户不知道操作是否成功。

内容的提问来源于stack exchange,提问作者jimmy8ball

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:37:29