Monday 13 February 2012

JSON and jqGrid Example

Below is a simple example of how I use a JSON object to fill a jqGrid. I was at first unable to fill the grid and it always came back empty until I inserted the following property value:
            
jsonReader: {
   repeatitems: false
}
My HTML:
<html>
  <head>
    <title>My Grid</title>
  </head>
  <body>
    <form id="form1">
      <table id="myGrid"></table>
      <div id="pager"></div>
    </form>
  </body>
</html>
My JavaScript:
//get this data from the cache
        var gridJson = { page: 1, total: 2, records: 10, rows: [
            { Id: 0, Label: "Custom Field 1", LastUpdatedDate: "10/02/2012" },
            { Id: 1, Label: "Custom Field 2", LastUpdatedDate: "10/02/2012"}]
        };

        //setup the grid
        $("#myGrid").empty().jqGrid({
            datatype: 'jsonstring',
            datastr: gridJson,
            colNames: ['Id', 'Custom Field Name', 'Last Update', 'Action'],
            colModel: [{ name: 'Id', index: 'Id', hidden: true, classes: 'id' },
                       { name: 'Label', index: 'Label', width: 500 },
                       { name: 'LastUpdatedDate', index: 'LastUpdatedDate', width: 200 },
                       { width: 132, sortable: false, classes: 'action', align: 'center'}],
            pager: jQuery('#pager'),
            jsonReader: {
                repeatitems: false
            },
            width: 832,
            height: "100%",
            scrollOffset: 20,
            rowNum: 10,
            rowList: [10, 15, 20, 25],
            sortname: 'Label',
            sortorder: "asc",
            viewrecords: true,
            hoverrows: false,
            caption: "",           
            beforeSelectRow: function (rowid, e) { return false; } //this disables row being highlighted when clicked
        });

Tuesday 7 February 2012

LINQ to XML Enum Extension Method Converter

Below are easy to use extension methods to extract a generic enum from an XML attribute using LINQ to XML:


    
public static class ExtensionMethods
    {
        public static string SafeAttribute(this XElement element, string key)
        {
            var attribute = element.Attribute(key);
            return attribute != null ? element.Attribute(key).Value : "";
        }

        public static T SafeAttribute<T>(this XElement element, string key)
        {
            var attribute = SafeAttribute(element, key);
            return !string.IsNullOrEmpty(attribute) ? (T)Enum.Parse(typeof(T), attribute) : default(T);
        }
    }

Any this is how you would call it:

var xml = XDocument.Load(filePath);
var e = xml.Element("Item").SafeAttribute<MyEnum>("myKey");