1

Bloente`enter image description here

namespace believe.Controllers { public class ProductController : Controller { private readonly IUnitOfWork _context; private readonly IWebHostEnvironment _hostEnvironment; public ProductController(IUnitOfWork context, IWebHostEnvironment hostEnvironment) { _context = context; _hostEnvironment = hostEnvironment; }

    public IActionResult Index()
    {
       
        return View();
    }
    //GET
   
  
    public IActionResult Delete(int? id)
    {
        if (id is null or 0)
        {
            return NotFound();
        }
        var obj = _context.Product.GetFirstOrDefault(c => c.Id == id);
        return View(obj);
    }
    [HttpPost]
    public IActionResult DeletePOST(int? id)
    {
        var obj = _context.Product.GetFirstOrDefault(c => c.Id == id);
        if (obj == null)
        {
            return NotFound();
        }
        _context.Product.Remove(obj);
       _context.Save();
        TempData["success"] = "Category deleted successfully";
        return RedirectToAction("Index");   
    }
    public IActionResult UpSert(int? id)
    {

        //Product product = new();
        //IEnumerable < SelectListItem > CategoryList = _context.Category.GetAll().Select(u=>new SelectListItem { Text = u.Name, Value = u.Id.ToString() });
        // IEnumerable<SelectListItem> CoverTypeList = _context.CoverType.GetAll().Select(u => new SelectListItem { Text = u.Name, Value = u.Id.ToString() });
        ProductVM productVM = new()
        {
            Product = new(),
         CategoryList =    _context.Category.GetAll().Select(u => new SelectListItem { Text = u.Name, Value = u.Id.ToString() }),
         CoverTypeList =  _context.CoverType.GetAll().Select(u => new SelectListItem { Text = u.Name, Value = u.Id.ToString() })


        };
        
        if (id is null or 0)
        {
            //create product

            //ViewBag.CategoryList = CategoryList;
            //ViewBag.CoverTypeList = CoverTypeList;  
            return View(productVM);
        }
        else
        {
            //update product
        }
      ;
        return View(productVM);
    }
    [HttpPost]
    public IActionResult UpSert(ProductVM obj, IFormFile? file)
    {
        

        if(ModelState.IsValid)
        {
            string wwwRootPath = _hostEnvironment.WebRootPath;
            if(file !=null)
            {
                string fileName = Guid.NewGuid().ToString();
                var uploads = Path.Combine(wwwRootPath, @"images\products");
                var extension = Path.GetExtension(file.FileName);
                using(var fileStreams = new FileStream(Path.Combine(uploads, fileName + extension),

FileMode.Create)) { file.CopyTo(fileStreams); } obj.Product.ImageUrl = @"\images\products" + fileName + extension; }

            _context.Product.Add(obj.Product);
            _context.Save();
            TempData["success"] = "Product  update successfully";
            return RedirectToAction("Index");
        }
        return View(obj);
        
    }
    #region API CALLS
    [HttpGet]
    public IActionResult GetAll()
    {
        var productList = _context.Product.GetAll();
        return Json(productList); 
    }
        

    #endregion

r code hereckquote` changed the return as you have showing but the pagge saying loading but it never load

[first screen shot of the controller][2secon screen shot\I'm new to coding world I'm trying to load my data form my database using DataTables, but for some reason I keep getting this error message. What am I doing wrong?

enter image description here

enter image description here

enter image description here

Trying to load the data from my database but it seems like my configuration is not working

4
  • 2
    add response from controller Commented Dec 6, 2022 at 3:17
  • Add Responce format. Commented Dec 6, 2022 at 5:02
  • welcome to stackoverflow baba! it would be nice if you could post code instead of screenshots. also, show us the controller code. Commented Dec 6, 2022 at 5:07
  • You shouldn't attached screenshot, you must share the code snippet, it stackoverflow, requirement and convension. Commented Dec 6, 2022 at 6:06

1 Answer 1

0

Trying to load the data from my database but it seems like my configuration is not working

I have reproduced your issue accordingly. This might be happend due to many reasons, if your data not in correct json format or if your column fields are in wrong format for instance, UpperCase, LowereCase.

In your scenario, you are doing wrong here: return Json(new { data = productList}); as per your view code, you should return like this return Json(productList); so your error will resolve.

You can try this way:

How to Debug:

enter image description here

Controller:

public IActionResult Index()
        {
            return View();
        }
        public ActionResult GetAll()
        {
            var productList = new List<product>()
            {
                new product(){ Id = 1, Title = "A", ISBN = "ISBN-1", Price = 10.1},
                new product(){ Id = 2, Title = "B", ISBN = "ISBN-2", Price = 10.1},
                new product(){ Id = 3, Title = "C", ISBN = "ISBN-3", Price = 10.1},
                new product(){ Id = 4, Title = "D", ISBN = "ISBN-4", Price = 10.1},
                new product(){ Id = 5, Title = "E", ISBN = "ISBN-5", Price = 10.1},



            };

            return Json(productList);

        }

Model:

public class product
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string ISBN { get; set; }
    public double Price { get; set; }
}

View:

<table id="myTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>ISBN</th>
            <th>Price</th>
           

        </tr>
    </thead>
</table>
@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "Admin/Product/GetAll",
                success: function (response) {
                    console.log(response);
                    $('#myTable').DataTable({
                        data: response,
                        columns: [
                            { data: 'id' },
                            { data: 'title' },
                            { data: 'isbn' },
                            { data: 'price' }
                        ]
                    });

                },
                error: function (response) {
                    alert(response.responseText);
                }
            });

        });
    </script>
}

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.