I try to showing data with jquery data table but the result is no value at all (only showing header) enter image description here

以下是我的查看脚本

@model IEnumerable<Vitashopper.Models.Goods>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table table-bordered table-striped" id="productTable">
    <tr>
        <th>ProductID</th>
        <th>ProductName</th>
        <th>BuyPrice</th>
        <th>SellPrice</th>
        <th>Stock</th>
        <th>Description</th>
        <th>Remarks</th>
    </tr>

</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css"</script>
<script src="https://cdn.datatables.net/autofill/2.5.1/css/autoFill.dataTables.min.css"></script>


@section Scripts
{

    <script type="text/javascript">
     $(document).ready(function () {
        $.ajax({
            url: '@Url.Action("GetData", "Goods")',
            method: 'get',
            dataType: 'json',
            success: function (data) {
                $('#productTable').DataTable({
                    data: data,
                    columns: [
                         { "data": "ProductId" },
                           { "data": "ProductName" },
                           { "data": "BuyPrice" },
                        { "data": "SellPrice" },
                        { "data": "Stock" },
                        { "data": "Description" },
                        { "data": "Remarks" },
                    ]
                });
            }
        });
    });

    </script>
}

这是我的控制器

public ActionResult GetData()
        {
            GoodsDBHandle dbhandle = new GoodsDBHandle();
            var goods = dbhandle.GetGoods();
            goods.ToList().ForEach(x => x.ProductId = x.ProductId);
            return View(goods);

        }

这是用于显示数据数据库句柄

public List<Goods> GetGoods()
        {
            connection();
            List<Goods> goodslist = new List<Goods>();

            SqlCommand cmd = new SqlCommand("GetAllGoods", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter sd = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();

            con.Open();
            sd.Fill(dt);
            con.Close();
            string json = JsonConvert.SerializeObject(dt);
            DataTable dt2 = JsonConvert.DeserializeObject<DataTable>(json);
            foreach (DataRow dr in dt2.Rows)
            {
                goodslist.Add(
                    new Goods
                    {
                        ProductId = Convert.ToInt32(dr["ProductID"]),
                        ProductName = Convert.ToString(dr["ProductName"]),
                        BuyPrice = Convert.ToDecimal(dr["BuyPrice"]),
                        SellPrice = Convert.ToDecimal(dr["SellPrice"]),
                        Stock = Convert.ToInt32(dr["Stock"]),
                        Description = Convert.ToString(dr["Description"]),
                        Remarks = Convert.ToString(dr["Remarks"])
                        
                    });

                
            }
            
            return goodslist;
        }

在控制器端,我也try 了使用Return Json(new { data = goods }, JsonRequestBehavior.AllowGet);,并且它与json输出一起正常工作

我的实现有问题吗?

推荐答案

确保正确导入jQuery

可以try 使用此脚本

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"> </script>
<script src="https://cdn.datatables.net/1.10.8/js/jquery.dataTables.min.js" defer="defer"></script>

<script>

    $(document).ready(function () {

        $('#myTable').DataTable(

            {

                "ajax": {

                    "url": "/Goods/GetData",

                    "type": "Get",

                    "datatype": "json"

                },

                "columns": [

                    { "data": "ProductId" },

                    { "data": "ProductName" },

                    { "data": "BuyPrice" },

                    { "data": "SellPrice" },

                    { "data": "Stock" },

                    { "data": "Description" },

                    { "data": "Remarks" },

                ]

            });

    });

</script>
<body>

    <div style="margin:300px;margin-top:60px">

        <table id="myTable" class="display">

            <thead>

                <tr>

                    <th>Product ID</th>

                    <th>Product Name</th>

                    <th>Buy Price</th>

                    <th>Sell Price</th>

                    <th>Stock</th>

                    <th>Description</th>

                    <th>Remarks</th>

                </tr>

            </thead>

        </table>

    </div>

</body>

这是加载json数据的控制器.

public JsonResult GetData()

        {

            GoodsDBHandle obj = new GoodsDBHandle();

            List<Goods> goodsList = obj.GetDataGoods();

            return Json(new { data = goodsList }, JsonRequestBehavior.AllowGet);

        }

然后是我从您这一端修改的DB调用 (实际上您的代码已经正确,但那里不需要jsonObject)

 public List<Goods> GetDataGoods()

        {

            List<Goods> goodsList = new List<Goods>();

            try

            {

                connection();

                {

                   SqlCommand cmd = new SqlCommand("GetAllGoods", con);
            cmd.CommandType = CommandType.StoredProcedure;

                    cmd.CommandType = CommandType.Text;

                    con.Open();

                    SqlDataReader sdr = cmd.ExecuteReader();

                    while (sdr.Read())

                    {

                        Goods g = new Goods();

                        g.ProductId = Convert.ToInt32(sdr["ProductId"].ToString());

                        g.ProductName = sdr["ProductName"].ToString();

                        g.BuyPrice = Convert.ToDecimal(sdr["BuyPrice"].ToString());

                        g.SellPrice = Convert.ToDecimal(sdr["SellPrice"].ToString());

                        g.Stock = Convert.ToInt32(sdr["Stock"].ToString());

                        g.Description = sdr["Description"].ToString();

                        g.Remarks = sdr["Remarks"].ToString();
                        goodsList.Add(g);

                    }

                }

            }

            catch (Exception ex)

            {

            }

            return goodsList;

        }

    }

然后对index.cshtml使用分部视图从json值获取所有数据

<div style="margin-top:20px">
    @Html.Partial("GetData")
</div>

我希望用这个示例脚本解决您的问题

Jquery相关问答推荐

将选定2个AJAX结果显示到模板中

在添加_renderMenu方法时,是什么原因导致jQuery UI AutoComplete抛出TypeError?

为什么我的 toFixed() 函数不起作用?

在 CSS3 或 jQuery 中将元素的宽度从 0% 设置为 100% 动画,它和它的包装器只需要它们需要的宽度,没有预先设置的宽度

使用 jQuery 和 HTML 导出为 CSV

jQuery 序列化不注册复选框

如何在 JQuery DataTable 中默认显示所有行

如何使div全屏?

javascript 正则表达式用于包含至少 8 个字符、1 个数字、1 个大写和 1 个小写的密码

如何使用 jQuery 为文本对齐动态添加样式

使用 时如何从 select2 中获取选定文本

使用 jQuery DataTables 时禁用第一列的自动排序

Jquery:如何判断元素是否具有某些 css 类/样式

jQuery: Select 所有具有自定义属性的元素

变量首字母大写

检测 jQuery UI 对话框是否打开

jQuery : eq() 与 get()

在某个点停止固定位置滚动?

detach()、hide() 和 remove() 之间的区别 - jQuery

jquery追加到列表的前面/顶部