8

I am using System.Web.Helpers.WebGrid control in ASP.NET Core application, I am getting the below error while rendering the grid

An unhandled exception occurred while processing the request.

ArgumentNullException: Value cannot be null.
 Parameter name: httpContext

System.Web.HttpContextWrapper..ctor(HttpContext httpContext)

at line

System.Web.Helpers.WebGrid objWebGrid = new System.Web.Helpers.WebGrid(Model.MeetingsObj);

Model:

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

Can anyone provide solution for the above error?

5
  • What is the value of Model.MeetingsObj? Commented Apr 10, 2017 at 12:49
  • @Luke , Model.MeetingsObj is a list Commented Apr 10, 2017 at 12:53
  • Please can you show us the definition of the list and any objects that it contains Commented Apr 10, 2017 at 12:54
  • @Luke, Added the model definition in question, Commented Apr 10, 2017 at 12:56
  • @Luke, the above code works fine in MVC5 app, I am getting the error only in ASP.NET Core Commented Apr 10, 2017 at 12:58

3 Answers 3

22

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");

//popup part
columns.Add(model => $"<a  data-modal='' data-id=\"{model.Id}\"     href='PasswordRestUser/{model.Id}'      id=\"ss\"  asp-    action=\"PR\" asp-route-id=\"@item.Id\" class=\"btn     btn-info\" '> PR <span class='glyphicon      glyphicon-user'> </span> </a>").Encoded(false);

})
.Filterable()
.Sortable()
.Pageable()
)

<div id='myModal' class='modal fade in'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>
        </div>
    </div>
</div>

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

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

5 Comments

It is similar to GRID.MVC in ASP.NET MVC but i has some issue like u need to pull entire model once and on that rows it play filtering, if we take 3 to 5 lakhs of records then it will start performance issue
you can overcome this part by using the manual paging ,and do the paging part yourself , it is simple i believe ,please check the sample, mvc6-grid.azurewebsites.net/Grid/ManualPaging
@Ali I like ur solution even in 2019 how would one use edit and delete buttons with the grid is their an easy way for a popup with the mv6 grid
sorry i missed your comment , unfortunately not with MVC grid , there is another solution for that jtable.org ,it od exactly what you need ,please check it ,
Thanks! I like the jtable and the mvc-6 grid. Thanks for mentioning these.
6

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

enter image description here

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

5 Comments

do you have a .net core 2.0 example?
@OracularMan same can be used with ASP.NET CORE 2.0 no issue in it
Following it to the "t". made sure @{ Layout = null; } getting the following errors [Error] TypeError: $('#dialog').dialog is not a function. (In '$('#dialog').dialog({ autoOpen: false, resizable: false, modal: true, width: 360 })', '$('#dialog').dialog' is undefined) Global Code (Definition:69) and... TypeError: undefined is not a function (near '...$('#grid').grid...')
@OracularMan are you using jquery dialog in you application. it is missing script reference.
using your awesome tutorial at c-sharpcorner.com/article/… now. Added System.Linq.Dynamic.Core; and Orderby works too. developing using .NET Core 2.0 VS 2017. Thx
0

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

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.