DataTables warning: table id=myTable - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
I have the following code and not sure what is wrong?
Product.js:
var dtable;
$(document).ready(function () {
dtable = $('myTable').DataTable({
"ajax": {
"url": "/Admin/Product/AllProducts" },
"Columns":
[
{ "data": "name" },
{ "data": "description" },
{ "data": "price" },
{ "data": "category.name" },
{ "data": "id", "render": function (data) { return } }
]
});
});
function RemoveProduct(url) { }
here is a clarification. I am not getting the data to show in index page eventhough the records are there in the db.
<div class="container p-4">
<div class="row p-3">
<div class="col-6">
<h2 class="text-primary">List of Products</h2>
</div>
<div class="col-6 text-end">
<a class="btn btn-primary" asp-action="CreateUpdate" asp-controller="Product"><i class="bi bi-plus-circle"></i> Create New Product</a>
</div>
</div>
</div>
<table id="myTable" class="table table-bordered table-striped" style="width:100%">
<thead>
<tr>
<th>
Product Name
</th>
<th>
Product Description
</th>
<th>
Price
</th>
<th>
Action
</th>
</tr>
</thead>
</table>
@section scripts{
@{
<script src="~/js/Product.js"></script>
}
}
controller:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using ShoppingCart2023.Repositories;
using ShoppingCart2023.ViewModels;
namespace ShoppingCart2023.Areas.Admin.Controllers
{
[Area ("Admin")]
public class ProductController : Controller
{
private IUnitOfWork _unitofWork;
private IWebHostEnvironment _hostingEnvironment;
public ProductController(IUnitOfWork unitOfWork, IWebHostEnvironment hostingEnvironment)
{
_unitofWork = unitOfWork;
_hostingEnvironment = hostingEnvironment;
}
#region APICALL
public IActionResult AllProducts()
{
var products = _unitofWork.Product.GetAll(includeProperties: "Category");
return Json(new { data = products });
}
#endregion
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult CreateUpdate(int? id)
{
ProductVM vm = new ProductVM()
{
Product = new(),
Categories = _unitofWork.Category.GetAll().Select(x => new SelectListItem()
{
Text = x.Name,
Value = x.Id.ToString()
})
};
if (id == null || id ==0)
{
return View(vm);
}
else
{
vm.Product = _unitofWork.Product.GetT(x => x.Id == id);
if (vm.Product == null)
{
return NotFound();
}
else
{
return View(vm);
}
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CreateUpdate(ProductVM vm, IFormFile? file)
{
if (ModelState.IsValid)
{
string fileName = String.Empty;
if (file != null)
{
string uploadDir = Path.Combine
(_hostingEnvironment.WebRootPath,
"ProductImage");
fileName = Guid.NewGuid().ToString() + "-" + file.FileName;
string filePath = Path.Combine(uploadDir, fileName);
if (vm.Product.ImageUrl != null)
{
var oldImagePath = Path.Combine(_hostingEnvironment.WebRootPath,
vm.Product.ImageUrl.TrimStart('\\'));
if (System.IO.File.Exists(oldImagePath))
{
System.IO.File.Delete(oldImagePath);
}
}
using(var fileStream = new FileStream(filePath, FileMode.Create))
{
file.CopyTo(fileStream);
}
vm.Product.ImageUrl = @"\ProductImage\" + fileName;
}
if (vm.Product.Id == 0)
{
_unitofWork.Product.Add(vm.Product);
TempData["success"] = "Product Created....Done!";
}
else
{
_unitofWork.Product.Update(vm.Product);
TempData["success"] = "Product Update....Done!";
}
_unitofWork.Save();
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
#region DeleteAPICALL
[HttpDelete]
public IActionResult Delete(int? id)
{
var product = _unitofWork.Product
.GetT(x => x.Id == id);
if (product == null)
{
return Json(new
{
success = false,
message = "Error Fetching data!"
});
}
else
{
var oldImagePath = Path.Combine(_hostingEnvironment.WebRootPath,
product.ImageUrl.TrimStart('\\'));
if (System.IO.File.Exists(oldImagePath))
{
System.IO.File.Delete(oldImagePath);
}
_unitofWork.Product.Delete(product);
_unitofWork.Save();
return Json(new
{
success = false,
message = "Error Fetching data!"
});
}
}
#endregion
}
}
finally the Product.js file:
var dtable;
$(document).ready(function () {
dtable = $('#myTable').DataTable({
"ajax": { "url": "/Admin/Product/AllProducts" },
"Columns": [
{ "data": "name" },
{ "data": "description" },
{ "data": "price" },
{ "data": "category.name" },
{
"data": "id",
"render": function (data) {
return `
<a href="/Admin/Product/CreateUpdate?id=${data}"><i class="bi bi-pencil-square"></i></a>
<a onclick=RemoveProduct("/Admin/Product/Delete/${data}")><i class="bi bi-trash"></i></a>
` }
}
]
});
});
function RemoveProduct(url) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
conformButtonText: 'Yes, delete it!',
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: url,
type: 'DELETE',
sucess: function (data) {
if (data.success) {
dtable.ajax.reload();
toastr.success(data.message);
}
else {
toastr.error(data.message);
}
}
});
}
})
}