Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Page History: Quick Reference - jqGrid

Compare Page Revisions



« Older Revision - Back to Page History - Newer Revision »


Page Revision: Tue, Oct 30, 2012, 9:32 AM


This page is a Draft. Its content is not complete and might contain errors.

Client Side

UI Code

<div id="uxUserGridDiv"><table id="uxUserGrid"></table></div>
<div id="uxUserGridPager"></div>

JavaScript Code

/*===============================================================================================*/
$(document).ready(function () {

    loadUserGrid();

});
/*===============================================================================================*/
function loadUserGrid() {

    $("#uxUserGrid").GridUnload();

    $("#uxUserGrid").jqGrid({
        url: '/Security/GetUsersForManager',
        editurl: '/Security/MaintainUserForManager',
        colModel: [
            {label: 'UserName', name: 'UserName',
                index: 'UserName', jsonmap: 'UserName',
                width: 150, align: 'left', editable: false
            },
            { label: 'Active', name: 'Active', index: 'Active', jsonmap: 'Active',
                width: 50, align: 'center', editable: true, edittype: 'checkbox',
                formatter: 'checkbox'
            },
            { label: 'Actions', name: 'Actions', index: 'Actions', width: 75, sortable: false,
                formatter: actionRowNoDelFormatter
            }
        ],
        pager: jQuery('#uxUserGridPager'),
        sortname: 'UserName',
        sortorder: 'asc',
        imgpath: '/Content/Themes/Redmond/Images',
        rowNum: -1,
        postData: { propertyId: getPropertyID },
        jsonReader: { id: 'PropertyID' } /* Primary Key - needed for delete operation */
        onSelectRow: function (id) { onGridRowSelect('uxUserGrid', id); }
    }).navGrid('#uxUserGridPager',
    {
        edit: false, add: false, del: false, search: false, refresh: true
    },
    updateDialog,
    updateDialog,
    updateDialog
    );
}

Dates Columns

In the colmodel for a date column, include the following, adjusting the newformat as needed.

align: 'center', formatter: 'date', formatoptions: { newformat: 'm/d/Y h:i:s A' },
                editoptions: { dataInit: function (el) { $(el).datepicker(); } }

Dropdown Columns

In the colmodel for a dropdown column, include the following.

editable: true, align: 'left', edittype: 'select',
formatter: function (cellValue, options, rowObject) {
    return rowObject.RelationType; /* display field for the dropdown */
},
editoptions: {
    value: $.ajax({
        type: "GET",
        url: "/Controller/Method",
        async: false
    }).responseText}

In addition, specify the following. (Both these fields should be returned by the server code behind url.
  • name and jsonmap = the name of the value field behind the dropdown
  • index = the name of the display field behind the dropdown

Server Code

Retrieve Data

public class SecurityController : JQGridController
{
    public ActionResult Index()
    {
        return View(new StaffViewModel());
    }

    [HttpGet]
    public JsonResult GetUsersForManager(string sidx, string sord, int page, int rows)
    {
        string currentUserName = HttpContext.User.Identity.Name;
        DataProvider dp = new DataProvider(Common.Common.RequestContext);
        IQueryable<UserResult> results = dp.GetUsersForManager(currentUserName);
        JsonResult result = JQGridResult<UserResult>(results, sidx, sord, page, rows);
        return result;
    }

    [HttpPost, Authorize]
    public JsonResult MaintainUserForManager(UserResult o, FormCollection formData)
    {
        int id;
        DataProvider dp;

        switch (formData["oper"])
        {
            case "edit":
                o = new UserResult
                {
                    UserName = formData["UserName"],
                    Active = formData.GetBool("Active")
                };

                dp = new DataProvider(Common.Common.RequestContext);
                dp.SaveUser(o);
                break;

            case "del":
                if (formData.TryGetInteger("id", out id))
                {
                    //dp = new DataProvider(Common.Common.RequestContext);
                    //dp.DeleteUser(id);
                }
                break;
        }
        return Json(null, JsonRequestBehavior.AllowGet);
    }

}

Reusable Code

PagingInfo class

This class encapsulates the paging parameters used by jqGrid.

public class PagingInfo
{
    public string sidx { get; set; }
    public string sord { get; set; }
    public int page { get; set; }
    public int rows { get; set; }
    public int totalPages { get; set; }
}

IQueryableHelper class

This class hosts the extension method CreatePagedResult, which converts an set of results into a of paged results expected by jqGrid.

public static class IQueryableHelper
{
    public static List<T> CreatePagedResult<T>(IQueryable<T> results, PagingInfo paging)
    {
        try
        {
            int pageIndex = Convert.ToInt32(paging.page) - 1;
            int pageSize = paging.rows;
            int totalRecords = results == null ? 0 : results.Count();

            if (pageSize > 0)
            {
                paging.totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
            }
            else
            {
                paging.totalPages = 1;
                pageSize = totalRecords;
            }

            if (!string.IsNullOrEmpty(paging.sidx))
            {
                if (string.IsNullOrWhiteSpace(paging.sord))
                    paging.sord = "asc";

                string sortString = string.Empty;

                var sortKeys = paging.sidx.Split(',');

                foreach (var sortKey in sortKeys)
                {
                    if (sortString.Length > 0)
                        sortString += ",";

                    sortString += sortKey + " " + paging.sord;
                }

                return results.OrderBy(sortString).Skip(pageIndex * pageSize).Take(pageSize).ToList<T>();
            }
            else
            {
                return results.Skip(pageIndex * pageSize).Take(pageSize).ToList<T>();
            }
        }
        catch (Exception ex)
        {
            paging.totalPages = 1;
            return results.ToList<T>();
        }
    }
}

JQGridController class

This class provides the JQGridResult method, which converts a List of results into a Json object expected by jqGrid.

public abstract class JQGridController : Controller
{
    protected JsonResult JQGridResult<T>(List<T> results, int page, int totalPages)
    {
        try
        {
            var jsonData = new
            {
                total = totalPages,
                page = page,
                records = results.Count(),
                rows = Json(results).Data
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        catch
        {
            return Json(null, JsonRequestBehavior.AllowGet);
        }
    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.