Home > Back-end >  ASP.NET MVC using C# and data tables
ASP.NET MVC using C# and data tables

Time:12-07

Bloente`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"  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

  • Related