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

ASP.NET MVC无EF,通过Ajax按ID获取数据并绑定DataTable

解决ASP.NET MVC中Ajax传递数据到DataTable的问题

一、确保控制器正确返回JSON数据

首先要保证控制器的Action能正确调用存储过程并返回符合格式的JSON数组。以下是示例代码:

using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
using YourProject.Models;

namespace YourProject.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult GetEmployeeById(int id)
        {
            List<Employee> employeeList = new List<Employee>();
            string connString = ConfigurationManager.ConnectionStrings["YourDBConnection"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connString))
            {
                using (SqlCommand cmd = new SqlCommand("SP_GetEmployeeById", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@EmployeeId", id);
                    conn.Open();

                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        employeeList.Add(new Employee
                        {
                            Id = (int)reader["Id"],
                            FullName = reader["FullName"].ToString(),
                            Department = reader["Department"].ToString(),
                            Position = reader["Position"].ToString(),
                            HireDate = (DateTime)reader["HireDate"]
                            // 对应你的Employee模型属性和存储过程返回字段
                        });
                    }
                    reader.Close();
                }
            }

            // 允许GET请求返回JSON,若用POST可移除JsonRequestBehavior.AllowGet并加[HttpPost]标签
            return Json(employeeList, JsonRequestBehavior.AllowGet);
        }
    }
}

二、视图中配置DataTable与Ajax请求

1. 基础HTML表格结构

在视图页面添加DataTable的容器:

<div class="container">
    <button id="loadEmployeeBtn">加载指定ID员工数据</button>
    <table id="employeeTable" class="display" style="width:100%">
        <thead>
            <tr>
                <th>员工ID</th>
                <th>姓名</th>
                <th>部门</th>
                <th>职位</th>
                <th>入职日期</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

2. 引入必要的依赖脚本

确保页面已引入jQuery和DataTable的CSS/JS:

<!-- jQuery -->
<script src="~/Scripts/jquery-3.6.0.min.js"></script>
<!-- DataTable样式 -->
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<!-- DataTable脚本 -->
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>

3. 修正Ajax与DataTable初始化代码

替换你现有有问题的Ajax代码,使用DataTable内置的ajax配置来加载数据:

$(document).ready(function () {
    $('#loadEmployeeBtn').click(function () {
        // 替换为实际要查询的员工ID,可从输入框/其他控件获取
        var targetEmployeeId = 5;

        // 初始化/重建DataTable
        $('#employeeTable').DataTable({
            destroy: true, // 若表格已初始化,先销毁再重新加载
            ajax: {
                url: '@Url.Action("GetEmployeeById", "Employee")', // 生成正确的路由地址
                type: 'GET',
                data: { id: targetEmployeeId }, // 传递指定ID参数
                dataSrc: '' // 控制器直接返回数组,无需嵌套的data属性
            },
            columns: [
                { data: 'Id' }, // 对应模型的Id属性
                { data: 'FullName' },
                { data: 'Department' },
                { data: 'Position' },
                { 
                    data: 'HireDate',
                    render: function (data) {
                        // 格式化日期显示
                        return new Date(data).toLocaleDateString();
                    }
                }
            ],
            // 可选:添加一些DataTable的配置项
            paging: false,
            searching: false
        });
    });
});

三、常见问题排查

  • 数据为空或不显示:检查控制器返回的JSON属性名是否与DataTablecolumns.data完全一致;验证存储过程是否能正确返回指定ID的员工数据。
  • Ajax请求失败:打开浏览器开发者工具(F12)查看Network标签,检查请求的URL是否正确、参数是否传递成功、控制器是否返回200状态码。
  • GET请求被阻止:确保控制器返回JSON时添加了JsonRequestBehavior.AllowGet,若使用POST请求,需给Action添加[HttpPost]标签,并将Ajax的type改为POST。
  • 依赖缺失:确认jQuery和DataTable的脚本/样式已正确引入,无404错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:06:28