Click here to Skip to main content
16,023,103 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to display customize jquery grid in view using following Controller & view code. But the view is not rendering on screen.


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Mvc;
using System.DirectoryServices;
using System.Web.Security;


namespace O365_WebApp_SingleTenant.Controllers
{
    public class HomeController : Controller
    {
        private const int TOTAL_ROWS = 999;
        private static readonly List<DataItem> _data = CreateData();

        public class DataItem
        {
            public string Mail { get; set; }
            public string SamAccountName { get; set; }
            public string DisplayName { get; set; }
        }

        public class DataTableData
        {
            public int draw { get; set; }
            public int recordsTotal { get; set; }
            public int recordsFiltered { get; set; }
            public List<DataItem> data { get; set; }
        }

        private static List<DataItem> CreateData()
        {
            try
            {
                Random rnd = new Random();
                List<DataItem> list = new List<DataItem>();
                string DomainPath = "LDAP://mycompanydomain.com";
                DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
                DirectorySearcher search = new DirectorySearcher(searchRoot);
                search.Filter = "(&(objectClass=user)(objectCategory=person))";
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("usergroup");
                search.PropertiesToLoad.Add("displayname");
                SearchResult result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int i = 1; i <= TOTAL_ROWS; i++)
                    {
                        result = resultCol[i];
                        if (result.Properties.Contains("samaccountname") &&
                                 result.Properties.Contains("mail") &&
                            result.Properties.Contains("displayname"))
                        {

                            DataItem item = new DataItem();
                            item.Mail = (String)result.Properties["mail"][0];
                            item.SamAccountName = (String)result.Properties["samaccountname"][0];
                            item.DisplayName = (String)result.Properties["displayname"][0];
                            list.Add(item);
                        }
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        private int SortString(string s1, string s2, string sortDirection)
        {
            return sortDirection == "asc" ? s1.CompareTo(s2) : s2.CompareTo(s1);
        }

        private int SortInteger(string s1, string s2, string sortDirection)
        {
            int i1 = int.Parse(s1);
            int i2 = int.Parse(s2);
            return sortDirection == "asc" ? i1.CompareTo(i2) : i2.CompareTo(i1);
        }

        private int SortDateTime(string s1, string s2, string sortDirection)
        {
            DateTime d1 = DateTime.Parse(s1);
            DateTime d2 = DateTime.Parse(s2);
            return sortDirection == "asc" ? d1.CompareTo(d2) : d2.CompareTo(d1);
        }


        private List<DataItem> FilterData(ref int recordFiltered, int start, int length, string search, int sortColumn, string sortDirection)
        {
            List<DataItem> list = new List<DataItem>();
            if (search == null)
            {
                list = _data;
            }
            else
            {
                // simulate search
                foreach (DataItem dataItem in _data)
                {
                    if (dataItem.Mail.ToUpper().Contains(search.ToUpper()) ||
                        dataItem.SamAccountName.ToString().Contains(search.ToUpper()) ||
                        dataItem.DisplayName.ToString().Contains(search.ToUpper()))
                    {
                        list.Add(dataItem);
                    }
                }
            }

            // simulate sort
            if (sortColumn == 0)
            {// sort Name
                list.Sort((x, y) => SortString(x.Mail, y.Mail, sortDirection));
            }
            else if (sortColumn == 1)
            {// sort Age
                list.Sort((x, y) => SortInteger(x.SamAccountName, y.SamAccountName, sortDirection));
            }
            else if (sortColumn == 2)
            {   // sort DoB
                list.Sort((x, y) => SortDateTime(x.DisplayName, y.DisplayName, sortDirection));
            }

            recordFiltered = list.Count;

            // get just one page of data
            list = list.GetRange(start, Math.Min(length, list.Count - start));

            return list;
        }

        // this ajax function is called by the client for each draw of the information on the page (i.e. when paging, ordering, searching, etc.). 
        public ActionResult AjaxGetJsonData(int draw, int start, int length)
        {
            string search = Request.QueryString["search[value]"];
            int sortColumn = -1;
            string sortDirection = "asc";
            if (length == -1)
            {
                length = TOTAL_ROWS;
            }

            // note: we only sort one column at a time
            if (Request.QueryString["order[0][column]"] != null)
            {
                sortColumn = int.Parse(Request.QueryString["order[0][column]"]);
            }
            if (Request.QueryString["order[0][dir]"] != null)
            {
                sortDirection = Request.QueryString["order[0][dir]"];
            }

            DataTableData dataTableData = new DataTableData();
            dataTableData.draw = draw;
            dataTableData.recordsTotal = TOTAL_ROWS;
            int recordsFiltered = 0;
            dataTableData.data = FilterData(ref recordsFiltered, start, length, search, sortColumn, sortDirection);
            dataTableData.recordsFiltered = recordsFiltered;

            return Json(dataTableData, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Search()
        {
            ViewBag.Message = "Search User";
            return View();
        }  
    }
}


HTML
<pre lang="C#"><script src="~/Scripts/jquery-1.7.2.js" ></script>
<script src="~/Scripts/DataTables/jquery.dataTables.js" ></script>
<link rel="stylesheet" type="text/css" href="~/Content/DataTables/css/jquery.dataTables.css">


<script>
    $(document).ready(function () {
        $('#example').dataTable({
            "processing": true, // control the processing indicator.
            "serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
            "info": true,   // control table information display field
            "stateSave": true,  //restore table state on pSamAccountName reload,
            "lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]],    // use the first inner array as the pSamAccountName length values and the second inner array as the displayed options
            "ajax":{
                "url": "@string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/Home/AjaxGetJsonData",
                "type": "GET"
            },
            "columns": [
                { "data": "Mail", "orderable" : true },
                { "data": "SamAccountName", "orderable": false },
                { "data": "DisplayName", "orderable": true }
            ],
            "order": [[0, "asc"]]
        });
    });
</script>

@*
    using fiddler, the above generate the following request
    http://localhost:50465//Home/AjaxGetJsonData?draw=1&columns[0][data]=Mail&columns[0][Mail]=&columns[0][searchable]=true&columns[0][orderable]=true&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=SamAccountName&columns[1][Mail]=&columns[1][searchable]=true&columns[1][orderable]=true&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=DisplayName&columns[2][Mail]=&columns[2][searchable]=true&columns[2][orderable]=true&columns[2][search][value]=&columns[2][search][regex]=false&order[0][column]=0&order[0][dir]=asc&start=0&length=10&search[value]=&search[regex]=false&_=1437007829254
*@

<div style="margin:30px;">
    Pimpale Page
    <table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr style="text-align:left;">
                <th>Mail</th>
                <th>DisplayName</th>
                <th>Full Name</th>
            </tr>
        </thead>
 
        <tfoot>
            <tr style="text-align:left;">
                <th>Mail</th>
                <th>DisplayName</th>
                <th>Full Name</th>
            </tr>
        </tfoot>
    </table>

</div>



What I have tried:

Calling new cshtml page containing table for the AD list
Posted
Comments
F-ES Sitecore 29-Jul-16 6:00am    
Put a breakpoint in the AjaxGetJsonData method and step through the code to see what is happening.
Richard Deeming 29-Jul-16 8:54am    
catch (Exception ex) { throw ex; }

Don't do that. You've just destroyed the stack-trace of the exception, making it much harder to track down any errors.

If you absolutely must catch and re-throw an exception, just use throw; - that way, the stack trace is preserved:
catch (Exception ex) { throw; }

But in this case, since you're not doing anything with the exception, there's no point in catching it in the first place. Just remove the try..catch block, and replace it with the contents of the try part.
deepak.dubal 11-Aug-16 5:37am    
I think this issue occurs because of Query string length is greater than 256 characters.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900