JG Vimalan's Blog

It is all about coding!

Dynamic columns in jqGrid

In this post we are going to see how to display jqGrid with dynamic columns.
I am using the following plugins and languages for preparing this article,
a. jqGrid 4.5.4 plugin
b. jQuery 1.8.2
c. ASP.NET WebForms
d. C#
e. Visual Studio 2012

Step 1:

I am assuming that you already have an ASP.NET project configured with jqGrid plugin.
The first thing to do is, create a class as shown below to hold the column header names, model names and actual data generated at runtime.

public class Dashboard
{
private List _model = new List();
//at runtime you will know the column names, set them here.
public List Model
{
get
{
return _model;
}
set
{
_model = value;
}
}

private List _headers = new List();
//if you want to give more meaningful names for column, set them here.
//The order of model name should match with header name
public List Headers
{
get
{
return _headers;
}
set
{
_headers = value;
}
}
//Store the actual data generated at runtime here.
//I converted datatable generated at runtime in to List<Dictionary<string, object>>
public List<Dictionary<string, object>> DashboardContent { get; set; }

}

Step 2:

In your ASP.NET page, define table controls as shown below,

<table id=”ReportGrid”></table>
<div id=”ReportGridPager”></div>

Step 3:

In the code behind, write the WebMethod that returns the Dashboard object.

[WebMethod]
public static Dashboard GetReportDashboard()
{
//In the ‘GetDailyDashboard’ method, you will get dynamic data from database
//and build the datatable at runtime. Then get the columns, headers from datatable and set it to
//Model and Headers property in Dashboard object. Also convert the datatable to
//List<Dictionary<string, object>> object and set it to DashboardContent property.

return ReportQueryManager.GetDailyDashboard();
}

Step 4:

In your javascript file, which holds the logic to build jqGrid on table object use the following code,

Basically, in the AJAX success method, get the Dashboard property values and set them to
jqGrid properties and bind the data to jqGrid.

$.ajax({
url: methodUrl, //set the method url here
dataType: “json”,
type: ‘POST’,
data: null,
contentType: “application/json; charset=utf-8”,
success: function (data) {
var dataArray = data.d //here you get the Dashboard object

var reportModel = dataArray.Model //Model property in Dashboard object
var header = dataArray.Headers ////Header property in Dashboard object
var dashboardData = dataArray.DashboardContent //Actual data with column

var ColModel = [];
for (index in reportModel ) {
var colName = reportModel[index]
var colWidth = 100
var isFixed = false
var sortTypeValue = “int”
var alignPosition = ‘center’

if (colName == “Name”) {
isFixed = true
colWidth = 300
sortTypeValue = “text”
alignPosition = ‘left’
}
ColModel.push({ name: colName, index: name, frozen: isFixed, width: colWidth, sorttype: sortTypeValue,
align: alignPosition });
}

var customButton = function (options) {
ReportGrid.jqGrid(‘navButtonAdd’, pageSelector, options);
ReportGrid.jqGrid(‘navButtonAdd’, ‘#ReportGrid’ + “_toppager”, options);
};

ReportGrid.jqGrid({
datatype: “local”,
mtype: “GET”,
cmTemplate: { sortable: true, resizable: true },
height: $(document).height() – reduceGridHeight,
rowNum: 20,
rowList: [],
altRows: true,
altclass: ‘gridAltRowClass’,
gridview: true,
pgbuttons: false,
loadonce: true,
shrinkToFit: false,
autoencode: true,
sortname: null,
width: $(“#SerReportGridWrapper”).width(),
ignoreCase: true,
viewrecords: true,
sortorder: “desc”,
pager: pageSelector,
pgtext: null,
scrollrows: true,
loadui: ‘disable’,
colNames: header, //set the header object here
colModel: SerColModel, //set the model object here
caption: “Dashboard”
});

ReportGrid.jqGrid(‘navGrid’, ‘#ReportGridPager’, {
view: true, add: false, edit: false, del: false, refresh: false, search: false, viewtext: ‘View Selected Row’
}, {}, {}, {}, {},
{ width: 400 });

ReportGrid.jqGrid(‘setFrozenColumns’);

customButton({
caption: “Export To Excel”,
title: “Export To Excel”,
onClickButton: function () {
if (serReportGrid.jqGrid(‘getGridParam’, ‘records’) == 0) {
Block(ReportGridBox, “No record(s) found to export”)
}
else {
Export()
}
}
});

ReportGrid[0].addJSONData(dashboardData);
},
error: function (d) {
if (d.statusText != ‘abort’) {
$.unblockUI();
$(“#ErrorMessage”).show()
}
}
});

Thats all. Now, you will be able to display dynamic columns in your jqGrid.

Advertisements

February 23, 2014 Posted by | ASP.NET, C#.NET, JavaScript, jqGrid, JQuery, JSON | , | 2 Comments

Editable Select Control in ASP.NET MVC 4 using Coffeescripter

I got a task where I need to display editable ‘select’ control using coffeescript in ASP.NET MVC 4 and twitter bootstrap.

Coffeescripter files are available here,

http://coffeescripter.com/code/editable-select/

The steps I followed to create editable “select” control are given below,

In MVC project, add reference to necessary coffeescript and jquery (I used jquery-1.9.1.js) and bootstrap files.

In View, add the following code,
<select id=”user_name_ddl” class=”editable-select”></select>

Open ‘jquery.editable-select.css’ (this file will be available in coffeescript pack) in your project and update the correct image location,

input.editable-select {
background: #FFF url(images/arrow-down.gif) right center no-repeat;
padding-right: 13px;
cursor:pointer;
}
Note: I copied the arrow-down image into an images folder in my MVC project.

In your custom .js file (if not, create one) add the following lines of code,

$(function () {
$(‘.editable-select’).editableSelect( {
bg_iframe: true, onSelect: function (list_item) {
$(‘#results’).html(‘List item text: ‘ + list_item.text() + ‘\ Input value: ‘+ this.text.val());
} } );

var select = $(‘.editable-select:first’);
var instances = select.editableSelectInstances();

if (instances != null && instances!= undefined && instances.length > 0)
instances[0].addOption(“Item 1”);
});

That’s it. Now, you will be able to see an editable select as shown below,

Snapshot

November 9, 2013 Posted by | ASP.NET MVC, JQuery | Leave a comment

Microsoft JScript runtime error: ‘JSON’ is undefined

I received this error when I tried to run my ASP.NET webpage in IE 8 Compatibility mode. JSON.parse function seems to be not working in IE 8 Compatibility mode.  The snapshot is given below,

json_error

In order to fix this issue, add reference to json2.min.js file in your ASP.NET webpage.  This file can be downloaded from NuGet, http://nuget.org/packages/json2/ . This will solve the issue.

April 9, 2013 Posted by | ASP.NET, JQuery, JSON | , , | Leave a comment

Enable / Disable ASP.NET TextBox control using jquery

The following code snippet will give you an idea for enabling or disabling an asp.net control using jquery,

Here, based on the option (true or false), I am enabling / disabling a textbox, setting its background color to lightgrey and clearing the text.

<head runat=”server”>
<script src=”Scripts/jquery-1.8.2.min.js” type=”text/javascript”></script>
<script type=”text/javascript” language=”javascript”>
$(document).ready(function () {
var optionChkBox = $(“#chkOption”)
optionChkBox.change(function () {
var status = optionChkBox.is(‘:checked’)

var nameTxtBox = $(“#txtBoxName”)
if (status) {
nameTxtBox.attr(‘disabled’, false)
nameTxtBox.css(“background-color”, “white”)
}
else {
nameTxtBox.val(”)
nameTxtBox.attr(‘disabled’, true)
nameTxtBox.css(“background-color”, “lightgray”)
}
})
});
</script>

October 16, 2012 Posted by | ASP.NET, JQuery, VS 2010 | Leave a comment

Save xml file in client machine without user interaction using asp.net

I got a task where I need to save an xml file in client machine whenever user vists a specific asp.net webpage. As my web application is IE compatible only, I have not verified this solution in other browsers.

In the following code I am going to read an xml file (data source) from the server and paste it in the client machine. The data source can be a session object, a variable in the code behind or a value in hidden field in asp.net page. My sample project structure is given below,

As a first step, add reference to jquery in your aspx page. Using jquery ajax, read the xml file. Then, using FileSystemObject ActiveX create the file in the target location. Then populate the file with the xml object.

Complete code is given below,

<head runat=”server”>
<title>Process XML using jQuery</title>
<script src=”Scripts/jquery-1.7.2.min.js” type=”text/javascript”></script>

<script type=”text/javascript” language=”javascript”>
$(document).ready(function () {;
$.ajax({
type: “GET”,
url: “UserInfo.xml”,
dataType: “xml”,
success: function (xmlObj) {
var fileSystemObject = new ActiveXObject(“Scripting.FileSystemObject”);
varFileObject = fileSystemObject.OpenTextFile(“C:\\Data\\UserInfo.xml”, 2, true, 0);
varFileObject.write(xmlObj.xml);
varFileObject.close();
alert(“Download complete”);
close();
},
error: function () {
alert(“Download failed. Please contact the administrator.”);
}
});
});

</script>

This does not require any user interaction. I am displaying javascript alert messages just for testing purpose.

In the line, varFileObject = fileSystemObject.OpenTextFile(“C:\\Data\\UserInfo.xml”, 2, true, 0); parameter true creates the file if it does not exist.

September 21, 2012 Posted by | ASP.NET, JavaScript, JQuery, VS 2010 | 6 Comments

DatePicker using jQuery

I got a task where I need to use datepicker from JQuery in my asp.net application.  The sample source code can be found here: 

http://cid-670f5e7529eed46d.office.live.com/self.aspx/.Public/jQuery/DatePicker.zip

So, when the user clicks on the textbox, the calendar will be displayed. The output will be as shown below,

o

It is really easy to implement and compatible with all browsers.

December 25, 2010 Posted by | ASP.NET, JQuery | 1 Comment