I try to showing data with jquery data table but the result is no value at all (only showing header)
以下是我的查看脚本
@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输出一起正常工作
我的实现有问题吗?