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

如何用C#、Vue.js实现记录过滤及编写GenerateTable JS函数

实现下拉框过滤并生成表格的JavaScript函数

问题背景

前端界面包含年份和月份下拉框(选项来自SQL Server数据库),点击「Filter」按钮后,需要根据选中的年月过滤数据并展示为表格。现有后端C#接口用于获取下拉框选项,前端按钮绑定了GenerateTable()函数,需编写该函数实现过滤逻辑。

现有后端代码

[HttpGet]
[Route("api/web/GetFilterYear")]
public List<Years> GetFilterRecords(string year)
{
    using (ApplicationDbContext db = new ApplicationDbContext())
    {
        List<Years> xx = new List<Years>();
        xx = db.Database.SqlQuery<Years>("GetYears").ToList();
        return xx;
    }
}

[HttpGet]
[Route("api/web/GetFilterMonth")]
public List<Years> GetFilterMonth(string month)
{
    using (ApplicationDbContext db = new ApplicationDbContext())
    {
        List<Years> xx = new List<Years>();
        xx = db.Database.SqlQuery<Years>("GetFM").ToList();
        return xx;
    }
}

现有前端按钮代码

<div class="col-sm-2"><button class="btn btn-sm btn-primary" style="margin-top:2px" onclick="GenerateTable()">Filter</button></div>

解决方案:编写GenerateTable函数

步骤说明

  1. 获取年份、月份下拉框的选中值
  2. 发起AJAX请求到后端过滤接口(注:现有后端接口仅用于获取下拉选项,需新增一个接收年月参数、返回过滤后数据的接口,比如api/web/GetFilteredData)
  3. 根据返回的数据动态生成表格并渲染到页面指定容器

完整JavaScript代码

function GenerateTable() {
    // 获取下拉框选中值(需确保下拉框id为yearSelect和monthSelect,可根据实际调整)
    const selectedYear = document.getElementById('yearSelect').value;
    const selectedMonth = document.getElementById('monthSelect').value;

    // 校验选中值
    if (!selectedYear || !selectedMonth) {
        alert('请选择年份和月份');
        return;
    }

    // 发起请求获取过滤后的数据
    fetch(`/api/web/GetFilteredData?year=${selectedYear}&month=${selectedMonth}`)
        .then(response => {
            if (!response.ok) throw new Error('请求失败');
            return response.json();
        })
        .then(data => {
            // 渲染表格到页面
            renderFilteredTable(data);
        })
        .catch(error => {
            console.error('获取数据出错:', error);
            alert('获取过滤数据失败,请重试');
        });
}

// 辅助函数:根据返回数据生成表格
function renderFilteredTable(data) {
    const tableContainer = document.getElementById('tableContainer');
    tableContainer.innerHTML = '';

    if (data.length === 0) {
        tableContainer.innerHTML = '<p>没有匹配的记录</p>';
        return;
    }

    // 创建表格元素
    const table = document.createElement('table');
    table.className = 'table table-bordered table-striped';

    // 生成表头(自动适配数据字段)
    const headerRow = document.createElement('tr');
    Object.keys(data[0]).forEach(key => {
        const th = document.createElement('th');
        th.textContent = key.charAt(0).toUpperCase() + key.slice(1);
        headerRow.appendChild(th);
    });
    table.appendChild(document.createElement('thead').appendChild(headerRow));

    // 生成表体内容
    const tbody = document.createElement('tbody');
    data.forEach(item => {
        const row = document.createElement('tr');
        Object.values(item).forEach(value => {
            const td = document.createElement('td');
            td.textContent = value;
            row.appendChild(td);
        });
        tbody.appendChild(row);
    });
    table.appendChild(tbody);

    // 插入到页面容器
    tableContainer.appendChild(table);
}

后端补充说明

现有接口未使用传入的年月参数,需新增专门的过滤接口:

[HttpGet]
[Route("api/web/GetFilteredData")]
public List<YourRecordModel> GetFilteredData(string year, string month)
{
    using (ApplicationDbContext db = new ApplicationDbContext())
    {
        // 调用带参数的存储过程或LINQ查询获取过滤后的数据
        return db.Database.SqlQuery<YourRecordModel>("GetFilteredRecords @Year, @Month", 
            new SqlParameter("@Year", year),
            new SqlParameter("@Month", month)).ToList();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:17:46