在ASP.NET Core中使用WebGrid

Sar*_*mar 4 c# asp.net-mvc asp.net-core-mvc asp.net-core

System.Web.Helpers.WebGrid在ASP.NET Core应用程序中使用控件,呈现网格时出现以下错误

An unhandled exception occurred while processing the request.

ArgumentNullException: Value cannot be null.
 Parameter name: httpContext

System.Web.HttpContextWrapper..ctor(HttpContext httpContext)
Run Code Online (Sandbox Code Playgroud)

在线

System.Web.Helpers.WebGrid objWebGrid = new System.Web.Helpers.WebGrid(Model.MeetingsObj);
Run Code Online (Sandbox Code Playgroud)

模型:

public class Meeting
    {

        public int MeetingId { get; set; }
        public string MeetingName { get; set; }
        public string Format { get; set; }
        public string Location { get; set; }
    }

    public class MeetingVM
    {
        public Meeting MeetingObj { get; set; }
        public List<Meeting> MeetingsObj { get; set; }
        public Boolean ShowGridHeader { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

谁能为上述错误提供解决方案?

Ali*_*Ali 12

您可以尝试使用其他组件,我建议使用MVC6网格 http://mvc6-grid.azurewebsites.net/

基本上使用几乎相同的语法,因此您当前的代码会有一些细微的变化,请检查以下示例代码

@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()
)
Run Code Online (Sandbox Code Playgroud)

它还具有许多其他功能,可以使.netcore变得更轻松

  • 抱歉,我错过了您的评论,不幸的是不是使用 MVC 网格,还有另一个解决方案 http://jtable.org/ ,它正是您所需要的,请检查它, (2认同)

Sai*_*war 5

您可以使用简单、轻量级和开源的客户端网格(jQuery DataTables Grid With ASP.NET CORE MVC)。

在此处输入图片说明

数据表网格所需的脚本和 Css

    <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>  
Run Code Online (Sandbox Code Playgroud)

ShowGrid 视图的完整代码片段

@{  
    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> 
Run Code Online (Sandbox Code Playgroud)

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;  
            }  

        }  
    }  
}  
Run Code Online (Sandbox Code Playgroud)

详细文章链接