Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WebGrid in ASP.NET Core

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?

like image 211
Saravana Kumar Avatar asked Apr 10 '17 12:04

Saravana Kumar


2 Answers

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

like image 158
Ali Avatar answered Sep 28 '22 00:09

Ali


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

like image 21
Saineshwar Avatar answered Sep 28 '22 00:09

Saineshwar