ASP.NET MVC with JTemplates – Part II
In my first part I of this two part series, I covered using Json, ASP.NET MVC, and jTemplate to bind to a simple html table.
The next part of this series is to ‘prettify’ the table using the jQuery plugin DataTables
DataTables supports using the same theme as used by jQuery UI, so I have decided to include this as well. Basically in about 4 lines of javascript, we can convert the previous simple table to a nice looking pageable, sortable, searchable grid!
The references are updated (see sample code):
<link href="<%= Url.Content("~/Content/Site.css") %>"
rel="stylesheet" type="text/css" /> <link href="<%= Url.Content("~/Content/jquery-ui-1.8.1.custom.css") %>"
rel="stylesheet" type="text/css" /> <link href="<%= Url.Content("~/Content/demo_table_jui.css") %>"
rel="stylesheet" type="text/css" /> <script type="text/javascript"
src="<%= Url.Content("~/Scripts/jquery-1.4.1.js") %>"></script> <script type="text/javascript"
src="<%= Url.Content("~/Scripts/jquery-ui.js") %>"></script> <script type="text/javascript"
src="<%= Url.Content("~/Scripts/jquery-jtemplates_uncompressed.js") %>"></script> <script type="text/javascript"
src="<%= Url.Content("~/Scripts/jquery.dataTables.js") %>"></script>
The next step is to apply the DataTables plugin to our table.
(If you had the demo code for part I, you might notice part II I had to make sure to define the thead and tbody tags in the table.)
<script type="text/javascript"> $(document).ready(function () { $.ajax({ type:"POST", url: "<%= Url.Action("GetData") %>", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data){ $("#jTemplateDemo").setTemplate($("#templateHolder").html()); $("#jTemplateDemo").processTemplate(data); $('#personTable').dataTable({ "bJQueryUI": true, "sPaginationType": "full_numbers", "aoColumns": [{ "sTitle": "First Name" }, { "sTitle": "Email" }] }); } }); }); </script>
I have included the previous javascript – the key section is the $(‘#personTable’).dataTable.
There are tons more functionality you can get from the plugin – including grid editing, server pagination, etc… (ie. saving state – (“bStateSave”:true)
I hope to create a third part of this series that will combine the edit features of the datatable with the ASP.NET MVC + json capability. This will be valuable to show the posting of json data as well as updating the underlying json data source for the template.
(by the way, there is an unintended “easter egg” in this post. If you recall the template grid TH was incorrectly labeled ‘Last Name’ instead of ‘Email’. By defining the aoColumns above, it overrides the ‘Last Name’ in the template and applies the ‘Email’ header. aoColumns is an optional parameter in this case).
I have included this code for your review – download here