loading columns dynamically for JQGrid using AjaxCall - asp.net-mvc

I need to load columns to Jqgrid Dynamically and am trying to follow jqGrid and dynamic column binding
Am trying in MVC. for Column name am fetching from Table(Which has a list of Columns to be displayed in GRID) and returning the Json data which is straightforward.
How do i implement for ColModel. For ex: i need to send JSon object like this dynamically
{name: 'Airport', formatter: UrlFmatter, width: 95, align: "center", index: 'AIRPORT', searchoptions: { sopt: ['eq', 'ne', 'cn']} }
{name: 'Country', width: 100, align: "center", index: 'Country', searchoptions: { sopt: ['eq', 'ne', 'cn']} }
How my design should be to send json to set the colModel ?
My UrlFmatter code
function UrlFmatter(cellvalue, options, rowObject) {
return "<a href='DetailResult?airportname=" + options.rowId + "' >" + cellvalue + "</a>";
}
How do i write as per your answer for formatting and unformatting ?
Thanks

I suppose that you have the problem with sending information about the formatter (formatter: UrlFmatter) inside of JSON. JSON strings don't support functions as the type of data. The most easy way to solve the problem seems me registering your formatter in the same way as standard formatters. For example is you want that your formatter have the name "myUrlFormatter" you can use the following
(function ($) {
'use strict';
/*jslint unparam: true */
$.extend($.fn.fmatter, {
myUrlFormatter: function (cellValue, options) {
// you should place here the code of
// your custom formatter UrlFmatter
}
});
$.extend($.fn.fmatter.myUrlFormatter, {
unformat: function (cellValue, options, elem) {
// you should place here the code of
// your custom unformatter
}
});
}(jQuery));
You should include the code after jquery.jqGrid.min.js (or after jquery.jqGrid.src.js). After such registration of the formatter you can use it in colModel as
{name: "Airport", index: "AIRPORT", formatter: "myUrlFormatter", width: 95,
align: "center", searchoptions: { sopt: ["eq", "ne", "cn"]} }
So the value of formatter property will be string (formatter: "myUrlFormatter") instead of the function (formatter: UrlFmatter).

Related

Possible to set dataLabels to display xAxis data instead of yAxis data in HighCharts?

so by reading the documents by default when you enable dataLabels on the chart it will render yAxis values, but is it possible to make it render xAxis values?
You can format labels in Highcharts in two ways:
Use dataLabels.formatter where you have access to this (point):
formatter: function () {
return this.x;
}
Demo: http://jsfiddle.net/BlackLabel/t2cek68m/1/
Use dataLabels.format, where you can put simple template:
format: "{x}"
Demo: http://jsfiddle.net/BlackLabel/t2cek68m/
Note:
You can use any property from a point, to show this in a label, both format and formatter can be used:
format: '{point.customValue}'
Or:
formatter: function () {
return this.point.customValue;
}
Where a point is defined as an object:
series: [{
data: [{
x: 10,
y: 15,
customValue: '10x10'
}]
}]
Demo: http://jsfiddle.net/BlackLabel/t2cek68m/3/
Yes it's possible just add this code :
dataLabels: {
enabled: true,
formatter: function() {
return this.x;
}
},
Fiddle

jqgrid and datepicker control giving error for new records

i binded by jqgrid with json returned from ajax. json has date in following format
11/1/2013 12:00:00 AM
in the colmodel i have specified the following
{ name: 'datecol', index: 'SignDate', width: '200', jsonmap: 'cell.SignDate', editable: true, sorttype: 'date',
editable: true, formatter: 'date', formatoptions: {
srcformat: 'm-d-Y H:i:s',
newformat: 'Y-M-d'
},
editoptions: { dataInit: initDateEdit },
initDateEdit = function(elem) {
setTimeout(function() {
$(elem).datepicker({
formatter: 'date', formatoptions: {
srcformat: 'm-d-Y H:i:s',
newformat: 'yy-M-d'
}
autoSize: true,
showOn: 'button', // it dosn't work in searching dialog
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
//$(elem).focus();
},100);
}
This displays the date correctly in the grid as
2013-Nov-01
but when i hit addnew record, the popup comes and when i select the date and hit submit, in the grid, the new record is showing
NaN-undefined-NaN
in the date column. what is wrong here?
when I use the same code as given in this link
http://www.ok-soft-gmbh.com/jqGrid/LocalFormEditing.htm
edit works fine, but when i add new row, the date comes as NaN-undefined-NaN
please help.
I think that the reason of the problem which you described is wrong parameters of jQuery UI Datepicker which you use. You use formatter and formatoptions parameters of datepicker which not exists. Instead of that you should use dateFormat option which format described here.
UPDATED: The main reason of the problem which you describe is wrong date format which you use. It's important to understand that srcformat and newformat of formatoptions should have PHP date format, but jQuery UI Datepicker supports another format which described here for example. The input data 11/1/2013 12:00:00 AM contains both date and time. On the other side jQuery UI Datepicker support date only. Because you use newformat: 'yy-M-d' then I suppose that you want just ignore the time part of the date. In the case I would suggest you to use
formatter: 'date',
formatoptions: {
srcformat: 'm/d/Y',
newformat: 'Y-m-d'
}
instead of
formatter: 'date',
formatoptions: {
srcformat: 'm-d-Y H:i:s',
newformat: 'Y-m-d'
}
which you use currently. Next problem is the dateFormat option of jQuery UI Datepicker. You have to use format which corresponds srcformat, but which uses correct format (described here). In case of srcformat: 'm/d/Y' you should use dateFormat: 'm/d/yy' instead of dateFormat: 'yy-m-dd' which you use in your jsfiddle demo.
The modified demo works now correctly.

jqgrid with custom column

I am using Jqgrid in my application. I wanted to create a column with 2 buttons. I want to have in column since the buttons may differ based on the data of the row. I googled it and I am able to found only creating a button using custom formatter option, but it appears only on double clicking a row or on edit of a row, but I want it to be displayed on column itself. Any help or link containing information will be appreciated. Below is my grid code.
Need to create an another column with buttons.
Edit:
var grid = $(gridId);
grid.jqGrid({
data: gridData,
datatype: "local",
gridview: true,
colModel: [
{
label: 'Employee Name', name: 'employeeName', width: 195, editable:true,
sortable:true, editrules:{required:true}
},
{
label: 'Address', name: 'address', width: 170, editable:true,
sortable:true,
editrules:{required:true}
},
{
label: 'Department', name: 'department', width: 120, editable:true,
sortable:true,
edittype:'custom',
editoptions: {
'custom_element' : populateReturnTypeAutocomplete,
'custom_value' : autocomplete_value
},
editrules:{required:true}
},
});
Okay add this to your colModal
{label: 'My Custom Column', name: 'custom', index:'custom' width: 120}
Now in gridComplete or loadComplete add this code
var grid = $("#grid"),
iCol = getColumnIndexByName(grid,'custom'); // 'custom' - name of the actions column
grid.children("tbody")
.children("tr.jqgrow")
.children("td:nth-child("+(iCol+1)+")")
.each(function() {
$("<div>",
{
title: "button1",
mouseover: function() {
$(this).addClass('ui-state-hover');
},
mouseout: function() {
$(this).removeClass('ui-state-hover');
},
click:
handle your click function here
}
).css({"margin-left": "5px", float:"left"})
.addClass("ui-pg-div ui-inline-save")
.attr('id',"customId")
.append('<span class="ui-button-icon-primary ui-icon ui-icon-disk"></span>')
.appendTo($(this).children("div"));
$("<div>",
{
title: "custombutton 2",
mouseover: function() {
$(this).addClass('ui-state-hover');
},
mouseout: function() {
$(this).removeClass('ui-state-hover');
},
click:
handle click here
}
).css({"margin-left": "5px", float:"left"})
.addClass("ui-pg-div ui-inline-custom")
.attr('id',"customButton2")
.append('<span class="ui-button-icon-primary ui-icon ui-icon-circle-check"></span>')
.appendTo($(this).children("div"));
Now these icons I'm adding here will be available with jquery ui.css and you will have to add one more function to your script which will get 'custom' column index for u in line first of above code.
var getColumnIndexByName = function(grid,columnName) {
var cm = grid.jqGrid('getGridParam','colModel'), i=0,l=cm.length;
for (; i<l; i+=1) {
if (cm[i].name===columnName) {
return i; // return the index
}
}
return -1;
};
I hope this helps.

Date-picker in jqGrid, simple example?

Does anyone know of an example of adding the jquery UI DatePicker (or some other perhaps) in the jqGrid? I'm trying to get it to work for an inline edit grid.
I have found a few examples, but nothing works. I would like something really simple!
My Grid setup (don't know if it's nessecary for this question):
$(function () {
var lastsel;
$("#list").jqGrid({
url: '#Url.Action("ExampleData", "Home")',
datatype: 'json',
mtype: 'GET',
colNames: ['Namn', 'Födelsedag', 'Adress', 'Stad'],
colModel: [
{ name: 'Name', index: 'Name', width: 130, editable: true },
{ name: 'Birthday', index: 'Birthday', width: 80, editable: true },
// DatePicker for birthday
{ name: 'Address', index: 'Address', width: 180, editable: true },
{ name: 'City', index: 'City', width: 80, editable: true },
],
pager: '#pager',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'Name',
sortorder: 'desc',
viewrecords: true,
gridview: true,
width: 700,
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('saveRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: '#Url.Action("Incoming", "Home")',
caption: 'Kontaktpersoner'
});
jQuery("#list").jqGrid('navGrid', "#pager", { edit: false, add: false, del: true });
jQuery("#list").jqGrid('inlineNav', "#pager");
As you can read in jqGrid documentation there is a dataInit option for this. What you should remember that this event is raised before the element is inserted into DOM, so use setTimeout just to be safe:
{ name: 'Birthday', index: 'Birthday', width: 80, editable: true editoptions: { dataInit: function(el) { setTimeout(function() { $(el).datepicker(); }, 200); } } },
The simplicity of the code depend of the format of the data which you fill in the 'Birthday' column. What you mostly need is to include
editoptions: { dataInit: function (elem) { $(elem).datepicker(); } }
as additionally property of 'Birthday' column. Sometimes one need define onSelect callback for the datepicker (see here), sometime one need to use setTimeout additionally or make some other customizations (see the answer) which includes working demos.

Display my data in jqGrid

In an ASP.NET MVC application using for the first time jqGrid.
I have a menu, I call "employee" from the menu in the master page like this :
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$(".mnuEmployee").click(function() {
$.post("/Employee/Index", null, function(data) {
$("#text").html(data);
});
});
});
</script>
In the controller, I have this :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index()
{
EmployeeModel model = new EmployeeModel();
model.List = _employeeService.List();
model.Languages = _languageService.List();
return View("Index", model);
}
In the View (Index.ascx), I have this :
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#sandgrid").jqGrid({
url: '/Employee/MyGridData/',
datatype: 'json',
mtype: 'GET',
height: 255,
width: 600,
colNames: ['Index', 'Name', 'Code'],
colModel: [
{ name: 'item_id', index: 'item_id', width: 65 },
{ name: 'item', index: 'item', width: 150 },
{ name: 'item_cd', index: 'item_cd', width: 100}],
pager: jQuery('#sandgridp'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'item_id',
sortorder: "desc",
viewrecords: true,
caption: 'Liste des employés'
});
});
</script>
<table id="sandgrid" cellpadding="0" cellspacing="0"></table>
<div id="sandgridp" style="text-align:center;"></div>
The problem is in this last part (I think), I have all datas in my model, I'd like display employee list in a jqGrid and languages (and more are coming) in classic textbox, textarea, ... How can I use the "model.List" (IList) to show in the grid ?
Thanks,
What is the reason to show languages in textbox/textarea? Did you mean select? If so then look at http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules, for the "select" edit type. Note that you can have multiselect list.
If you just want to display languages, then do this in your model:
model.Languages = string.Join(_languageService.List().Select(x => x.Name).ToArray(), ",");
And then jqGrid will display your languages as a string, comma-separated.
But I'd suggest you to decide (since it's not clear from the Q):
how you want to display languages/list
do you want to edit them and how
Also take a look at custom formatters http://www.trirand.com/jqgridwiki/doku.php?id=wiki:custom_formatter, you can write a function to convert your languages list into anything you want, on input you get data, on output you return string with any HTML. Don't forget "unformatter" if you need to edit the cell value. For example, I use custom formatter to display checkbox images instead of true/false text.
I'm a little confused. You have your jqGrid set up to do an AJAX query for it's data as JSON so there's no need to include in in the Index view's model.
url: '/Employee/MyGridData/',
datatype: 'json',
To use the AJAX method your controller needs a MyGridData action.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult MyGridData ()
{
var list = _employeeService.List();
return Json(list);
}
Also, the name and index properties in the colModel must match the property names in your model.

Resources