简体   繁体   English

ASP.NET MVC 使用 C# 和 data.tables

[英]ASP.NET MVC using C# and data tables

Blo ente` enter image description here Blo ente`在此处输入图像描述

namespace believe.Controllers { public class ProductController: Controller { private readonly IUnitOfWork _context; namespace believe.Controllers { public class ProductController: Controller { private readonly IUnitOfWork _context; private readonly IWebHostEnvironment _hostEnvironment;私有只读 IWebHostEnvironment _hostEnvironment; public ProductController(IUnitOfWork context, IWebHostEnvironment hostEnvironment) { _context = context; public ProductController(IUnitOfWork context, IWebHostEnvironment hostEnvironment) { _context = context; _hostEnvironment = 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); FileMode.Create)) { file.CopyTo(fileStreams); } obj.Product.ImageUrl = @"\images\products" + fileName + extension; } obj.Product.ImageUrl = @"\images\products" + 文件名 + 扩展名; } }

 _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 here ckquote` changed the return as you have showing but the pagge saying loading but it never load r code here ckquote` 改变了你所显示的返回,但是页面说加载但它从未加载

[first screen shot of the controller][2 secon 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. [控制器的第一个屏幕截图][2秒屏幕截图\我是编码世界的新手我正在尝试使用 DataTables 从我的数据库加载我的数据,但由于某种原因我不断收到此错误消息。 What am I doing wrong?我究竟做错了什么?

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

Trying to load the data from my database but it seems like my configuration is not working尝试从我的数据库加载数据,但我的配置似乎不起作用

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.这可能由于多种原因而发生,如果您的数据不是正确的json format ,或者如果您的列字段格式错误,例如大写、小写。

In your scenario, you are doing wrong here: return Json(new { data = productList});在您的场景中,您在这里做错了: return Json(new { data = productList}); as per your view code, you should return like this return Json(productList);根据您的视图代码,您应该像这样return Json(productList); so your error will resolve.所以你的错误会解决。

You can try this way:你可以试试这样:

How to Debug:如何调试:

在此处输入图像描述

Controller: 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: 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: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM