Using WebGrid in ASP.NET Core

浪子不回头ぞ 提交于 2019-12-05 17:09:17

You may try to use another component , i recommend the MVC6 grid http://mvc6-grid.azurewebsites.net/

basically it use almost same syntax ,so there will be minor changes to your current code ,please check the below sample code

@model IEnumerable<PersonModel>

@(Html
.Grid(Model)
.Build(columns =>
{
    columns.Add(model => model.Name).Titled("Name");
    columns.Add(model => model.Surname).Titled("Surname");

    columns.Add(model => model.Age).Titled("Age");
    columns.Add(model => model.Birthday).Titled("Birth date");
    columns.Add(model => model.IsWorking).Titled("Employed");
})
.Filterable()
.Sortable()
.Pageable()
)

it also has many other features that will make thing easier with .netcore

You can use Client side Grid (jQuery DataTables Grid With ASP.NET CORE MVC) which is simple, lightweight and open Sources.

Script and Css Required for DataTables Grid

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  

    <link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />  

    <link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />  
    <link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />  

    <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>  
    <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>  

Complete code Snippet of ShowGrid View

@{  
    Layout = null;  
}  

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />  

<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />  
<link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />  

<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>  
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>  

<div class="container">  
    <br />  
    <div style="width:90%; margin:0 auto;">  
        <table id="example" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">  
            <thead>  
                <tr>  
                    <th>CustomerID</th>  
                    <th>Name</th>  
                    <th>Address</th>  
                    <th>Country</th>  
                    <th>City</th>  
                    <th>Phoneno</th>  
                    <th>Edit</th>  
                    <th>Delete</th>  
                </tr>  
            </thead>  
        </table>  
    </div>  
</div>  

<script>  

        $(document).ready(function ()  
        {  
            $("#example").DataTable({  
                "processing": true, // for show progress bar  
                "serverSide": true, // for process server side  
                "filter": true, // this is for disable filter (search box)  
                "orderMulti": false, // for disable multiple column at once  
                "ajax": {  
                    "url": "/DemoGrid/LoadData",  
                    "type": "POST",  
                    "datatype": "json"  
                },  
                "columnDefs":  
                [{  
                    "targets": [0],  
                    "visible": false,  
                    "searchable": false  
                }],  
                "columns": [  
                    { "data": "CustomerID", "name": "CustomerID", "autoWidth": true },  
                    { "data": "Name", "name": "Name", "autoWidth": true },  
                    { "data": "Address", "name": "Address", "autoWidth": true },  
                    { "data": "Country", "name": "Country", "autoWidth": true },  
                    { "data": "City", "name": "City", "autoWidth": true },  
                    { "data": "Phoneno", "name": "Phoneno", "autoWidth": true },  
                    {  
                        "render": function (data, type, full, meta)  
                        { return '<a class="btn btn-info" href="/DemoGrid/Edit/' + full.CustomerID + '">Edit</a>'; }  
                    },  
                    {  
                        data: null, render: function (data, type, row)  
                        {  
                            return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";  
                        }  
                    },  
                ]  

            });  
        });  


    function DeleteData(CustomerID)  
        {  
            if (confirm("Are you sure you want to delete ...?"))  
            {  
                Delete(CustomerID);  
            }  
            else  
            {  
                return false;  
            }  
        }  


        function Delete(CustomerID)  
    {  
        var url = '@Url.Content("~/")' + "DemoGrid/Delete";  

            $.post(url, { ID: CustomerID }, function (data)  
                {  
                    if (data)  
                    {  
                        oTable = $('#example').DataTable();  
                        oTable.draw();  
                    }  
                    else  
                    {  
                        alert("Something Went Wrong!");  
                    }  
                });  
    }  

</script> 

Complete code Snippet of DemoGridController

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Mvc;  
using ExampleGrid.Models;  
using System.Linq.Dynamic;  
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860  

namespace ExampleGrid.Controllers  
{  
    public class DemoGridController : Controller  
    {  
        private DatabaseContext _context;  

        public DemoGridController(DatabaseContext context)  
        {  
            _context = context;  
        }  
        // GET: /<controller>/  
        public IActionResult ShowGrid()  
        {  
            return View();  
        }  

        public IActionResult LoadData()  
        {  
            try  
            {  
                var draw = HttpContext.Request.Form["draw"].FirstOrDefault();  
                // Skiping number of Rows count  
                var start = Request.Form["start"].FirstOrDefault();  
                // Paging Length 10,20  
                var length = Request.Form["length"].FirstOrDefault();  
                // Sort Column Name  
                var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();  
                // Sort Column Direction ( asc ,desc)  
                var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();  
                // Search Value from (Search box)  
                var searchValue = Request.Form["search[value]"].FirstOrDefault();  

                //Paging Size (10,20,50,100)  
                int pageSize = length != null ? Convert.ToInt32(length) : 0;  
                int skip = start != null ? Convert.ToInt32(start) : 0;  
                int recordsTotal = 0;  

                // Getting all Customer data  
                var customerData = (from tempcustomer in _context.CustomerTB  
                                    select tempcustomer);  

                //Sorting  
                if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))  
                {  
                    customerData = customerData.OrderBy(sortColumn + " " + sortColumnDirection);  
                }  
                //Search  
                if (!string.IsNullOrEmpty(searchValue))  
                {  
                    customerData = customerData.Where(m => m.Name == searchValue);  
                }  

                //total number of rows count   
                recordsTotal = customerData.Count();  
                //Paging   
                var data = customerData.Skip(skip).Take(pageSize).ToList();  
                //Returning Json Data  
                return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });  

            }  
            catch (Exception)  
            {  
                throw;  
            }  

        }  
    }  
}  

Link for Detail Article

I port open sourced WebGrid using ASP.NET Core and package is now on NuGet AndreyKurdiumov.AspNetCore.Helpers - version 0.2.0

This package trying to be in-place replacement for the WebGrid usage. But I don't yet manage to make this happens 100%.

Changes which should be done

  1. Add following lines in the _ViewImports.cshtml

    @using AndreyKurdiumov.AspNetCore.Helpers
    @inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
    
  2. Where WebGrid constructed should be add contructor parameter HttpContextAccessor

     var grid = new WebGrid(HttpContextAccessor, source: this.Model.Tables,
             defaultSort: "TableName",
             rowsPerPage: 30);
    

This is as simple as possible for migration existing codebase which I manage to implement.

The source code https://github.com/kant2002/AspNetCore.Helpers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!