How to pass values from Jqgrid onselect row to another grid - asp.net-mvc

I have to get value from Jqgrid Selected row and populate one more grid with datas based on the selected value from the master grid. I dont want to use master detail or subgrdi in Jqgrid. Since I am using MVC, is there any way to populate the second jqgrid in one more view?
I am not able to get the column value on selected row to post it to the second grid.
here is my code
$(document).ready(function() {
$("#UBSImageList").jqGrid({
url: '<%= Url.Content("~/UpdateBatchStatus/UBSDataJson/") %>',
datatype: "json",
mtype: 'POST',
colNames: ['BatchImageName'],
colModel: [
{name:'BatchImageName', index:'BatchImageName', align: 'left', width: 40, editable: false ,sortable: true}
],
rowNum: 20,
rowList: [10, 20, 30, 50],
pager: jQuery('#UBSImagePager'),
viewrecords: true,
imgpath: '<%= Url.Content("~/Content/Scripts/themes/basic/images")%>',
sortname: 'BatchImageName',
sortorder: "asc",
autowidth: true,
caption: 'Client Payor Group',
height: 350
});
$('#UBSImageList').setGridParam({
onSelectRow: function(id) {
window.location = '/UpdateBatchStatus/Details?id=' + id;
}
});
}

You can get rows on server with the following code. From here you can check how to populate the second jqgrid.
<script type="text/javascript">
$(document).ready(function(){
var grid = jQuery("#Jqgrid1");
jQuery("#m1").click( function() {
var s;
var rowcells=new Array();
s = grid.getGridParam('selarrrow');
//alert(s);
if(s.length)
{
for(var i=0;i<s.length;i++)
{
var entirerow = jQuery("#Jqgrid1").jqGrid('getRowData',s[i]);
rowcells.push($.param(entirerow));
}
}
$.ajax({
url: "/jqSubGrid.aspx",
type: "POST",
data: rowcells.join('||'),
success: function(html) {
alert(html);
}
});
});
});
</script>
Get Selected rows

Related

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.

asp.net mvc jqgrid submit grid using a button outside of the grid

I'm new to jqgrid and MVC. My Jqgrid is in multi select mode, and I want to submit all selected items on the grid to the controller by clicking on a button (tbrSave) outside of the grid.
#using (Html.BeginForm("Save", "Home"))
{
<button type="submit" id="tbrSave" class="toolbar">
<span title="Config" class="icon-32-save"></span>Save</button>
<script src="#Url.Content("~/Scripts/grid.locale-en.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.jqGrid.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.custom.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var lastSelectedRow;
$('#jqGridCategoryCreate').jqGrid({
//url from wich data should be requested
url: 'CategoriesList',
//type of data
datatype: 'json',
editurl: '#Url.Action("UpdateCategory")',
//url access method type
mtype: 'POST',
//columns names
colNames: ['CategoryId', 'Category Name', 'Display Order', 'Is Featured Product'], //columns model
colModel: [
{ name: 'Id', index: 'Id', align: 'left', editable: false },
{ name: 'Name', index: 'Name', align: 'left', editable: false },
{ name: 'DisplayOrder', index: 'DisplayOrder', align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 10 }, editrules: { required: true} },
{ name: 'IsFeaturedProduct', index: 'IsFeaturedProduct', align: 'left', editable: true, edittype: 'text', edittype: 'checkbox', editoptions: { maxlength: 10, value: '1:Yes;0:No' }, formatter: 'checkbox', editrules: { required: true}}],
//pager for grid
pager: $('#jqPagerCategoryCreate'),
//number of rows per page
rowNum: 10,
//initial sorting column
sortname: 'Id',
//initial sorting direction
sortorder: 'asc',
//we want to display total records count
viewrecords: true,
multiselect: true,
//grid width
width: 'auto',
//grid height
height: 'auto',
ondblClickRow: function (id) {
if (id && id != lastSelectedRow) {
//save changes in row
jQuery('#jqGridCategoryCreate').saveRow(lastSelectedRow);
$.lastSelectedRow = id;
//trigger inline edit for row
$('#jqGridCategoryCreate').editRow(lastSelectedRow, true);
}
}
});
$('#jqGridCategoryCreate').jqGrid('navGrid', '#jqPagerCategoryCreate',
{ add: false, del: true, edit: false, search: false },
{ width: 'auto', url: '/Category/Edit' },
{ width: 'auto', url: 'SaveCustomLanguageData' },
{ width: 'auto', url: '/Category/Delete' });
function getSelectedRows() {
//make sure all items must be in view mode before submitting.
jQuery('#jqGridCategoryCreate').saveRow(lastSelectedRow);
var rows = $("#jqGridCategoryCreate").jqGrid('getGridParam', 'selarrrow');
var categories = [];
$.each(rows, function (index, rowId) {
var gridRow = $("#jqGridCategoryCreate").getRowData(rowId);
var category = { "Id": rowId,
"DisplayOrder": gridRow['DisplayOrder']
};
categories.push(category);
});
}
});
</script>
}
How can I attach getSelectedRows to the grid in order to post it to Controller ("Save").
Thanks a mil.
Nam Vo.
This would involve following steps
1) Create a anchor link on your razor view
<a id="somelink" href="">Select Multiple Accounts</a>
2) Create a click event handler for anchor link created above
$('#somelink').click(function () {
var multiplerowdata = jQuery("#grid").getGridParam('selarrrow');
$.ajax({ type: 'POST',
url: '#Url.Action("YourController", "YourActionMethod")',
data: JSON.stringify(multiplerowdata),
traditional: true,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { alert("row submited"); }
});})
3) At times you may get javascript error of JSON is not defined, this can be solved by inserting meta tags in shared\_layout.cshtml page as shown below
<meta http-equiv="X-UA-Compatible" content="IE=8" />
4) YourActionMethod inside YourController should like be somewhat like this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult YourActionMethod(List<string> datarow)
{
//return "sucessfully validated";
return null;
}

How to enable excel export button for jqGrid

Hello
I want to show "export to excel" button in the pager of jqgrid. I tried many ways, read many articles/posts, but I don't see this button. Documentation does not have anything useful too. Which actions should I do to see this button
Ps. I use ASP.NET MVC
PSS. my code is
<link href="../../Scripts/jquery.UI/css/redmond/jquery-ui-1.8.1.custom.css" rel="Stylesheet"
type="text/css" />
<link href="../../Scripts/jquery.jqGrid/css/ui.jqgrid.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/i18n/grid.locale-ru.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/jquery.jqGrid.min.js"></script>
<table id="EmployeeTable">
</table>
<div id="EmployeeTablePager">
</div>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('#EmployeeTable').jqGrid({
url: '/Employee/EmployeeData',
datatype: "json",
mtype: 'POST',
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
repeatitems: false,
id: ""
},
colNames: ['Id', 'Имя', 'Фамилия', 'Email', 'Date'],
colModel: [
{ name: 'Id', width: 20 },
{ name: 'FirstName', width: 105 },
{ name: 'LastName', width: 100 },
{ name: 'Email', width: 150 },
{ name: 'Date', width: 150, formatter: ndateFormatter }
],
pager: '#EmployeeTablePager',
excel: true,
viewrecords: true
}).jqGrid('navButtonAdd',
'#EmployeeTablePager',
{ caption: " Export to Excel ",
buttonicon: "ui-icon-bookmark",
onClickButton: genCSV, position: "last"
});
});
function genCSV() {
alert('a');
}
function ndateFormatter(cellval, opts, rwdat, _act) {
var time = cellval.replace(/\/Date\(([0-9]*)\)\//, '$1');
var date = new Date();
date.setTime(time);
return date.toDateString();
}
</script>
but I don't see the excel import button.
http://ru.magicscreenshot.com/jpg/t97BDzCIO0Q.html
why?
Assuming markup of
<table id="jqgrid"></table>
<div id="pager"></div>
Something along the lines of
$('#grid')
.jqGrid({
datatype: "clientSide",
height: 190,
colNames: headers,
colModel: model,
multiselect: true,
pager: '#pager',
pgbuttons: false,
pginput: false,
caption: "Random Data",
deselectAfterSort: false,
width: 930
})
.jqGrid('navButtonAdd',
'#pager',
{caption:" Export to Excel ",
buttonicon:"ui-icon-bookmark",
onClickButton: genCSV, position:"last"});
genCSV will be a JavaScript function that will make the call to the controller action to generate a CSV file.
Here's an example, in combination with jQuery flot. Create some data, select some grid rows and then click the generate graph button in the bottom left of the grid to plot the points. Note that this will not work in Internet Explorer less than 8 as it requires support for the HTML 5 canvas element (and I haven't bothered to include excanvas).
EDIT:
Your markup is not working because you need to initialize a navGrid before being able to set a custom button (see note on page). You can do this like so
jQuery(document).ready(function () {
jQuery('#EmployeeTable').jqGrid({
url: '/Employee/EmployeeData',
datatype: "json",
mtype: 'POST',
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
repeatitems: false,
id: ""
},
colNames: ['Id', 'Имя', 'Фамилия', 'Email', 'Date'],
colModel: [
{ name: 'Id', width: 20 },
{ name: 'FirstName', width: 105 },
{ name: 'LastName', width: 100 },
{ name: 'Email', width: 150 },
{ name: 'Date', width: 150, formatter: ndateFormatter }
],
pager: '#EmployeeTablePager',
excel: true,
viewrecords: true
})
/* Need to initialize navGird before being able to set any custom buttons */
.jqGrid('navGrid', '#EmployeeTablePager', {
add: false,
edit: false,
del: false,
search: false,
refresh: false
}).jqGrid('navButtonAdd',
'#EmployeeTablePager',
{ caption: " Export to Excel ",
buttonicon: "ui-icon-bookmark",
onClickButton: genCSV, position: "last"
});
});
function genCSV() {
alert('a');
}
function ndateFormatter(cellval, opts, rwdat, _act) {
var time = cellval.replace(/\/Date\(([0-9]*)\)\//, '$1');
var date = new Date();
date.setTime(time);
return date.toDateString();
}
What I did was to create a csv file on the server and display a download link next to the grid in my view.
It's not as slick as what you have in mind but it is quick and easy to implement.
Extension method to create a csv file from a list (from another post on SO):
public static string AsCsv<T>(this IEnumerable<T> items)
where T : class
{
var csvBuilder = new StringBuilder();
var properties = typeof(T).GetProperties();
foreach (T item in items)
{
//string line = properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray().Join(",");
string line= string.Join(", ", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
csvBuilder.AppendLine(line);
}
return csvBuilder.ToString();
}
private static string ToCsvValue<T>(this T item)
{
if (item is string)
{
return string.Format("\"{0}\"", item.ToString().Replace("\"", "\\\""));
}
double dummy;
if (double.TryParse(item.ToString(), out dummy))
{
return string.Format("{0}", item.ToString());
}
return string.Format("\"{0}\"", item.ToString());
}
Controller:
model.AListOfData.ToArray().AsCsv();
using (StreamWriter sw = System.IO.File.CreateText(errorFilePath))
{
sw.Write(values);
}
model.ErrorFullFileName = errorFilePath;
In the view:
<%=Html.ImageLink("", "AssetUpload", "DownloadErrors", "/?filename=" + Model.ErrorFullFileName, "/Content/Icons/excel.png", "Download errors and warnings", "imagelink")%>
I used this and it works pretty well
jQuery("#table_resultats").jqGrid('navGrid', "#yourpager").jqGrid( //#pager
'navButtonAdd', "#yourpager", {
caption : "Excel export",
buttonicon : "ui-icon-arrowthickstop-1-s",
onClickButton : null,
position : "first",
title : Excel export,
cursor : "pointer"
});

Multiple jQgrids in jQueryui Tabs

I am having an issue that I need help with. I have 3 jQueryUI Tabs. The first holds a grid of items. The second holds a grid of Work Orders. The third just fires an alert to verify the show function is working. Problem is I have no grid on the second tab. First one loads fine. If I comment out the code for the first tab, the second grid shows up fine. Third tab fires an alert every time. I have a lightbox that i use to edit items on select which works fine. Here's the relevant code:
jQuery(document).ready(function () {
$('#tabs').tabs({
show: function(event, ui) {
if(ui.index == 0)
{
jQuery("#list1").jqGrid({
...
pager: '#pager1',
...
jQuery("#list1").jqGrid('navGrid','#pager1',{edit:false,add:false,del:false});
}
else if(ui.index == 1)
{
$("#list").jqGrid({
...
pager: '#pager',
....
onSelectRow: function(id){
if(id){
alert(id);
onclick=openbox('Edit Work Order', 1);
...
else if(ui.index == 2)
{
alert('tab2');
}
}
I appreciate any help you can give.
Probably your problem exist because you used the HTML code
<div id="tabs-1">
<table id="list1"><tr><td/></tr></table>
<div id="pager1"/>
</div>
<div id="tabs-2">
<table id="list"><tr><td/></tr></table>
<div id="pager"/>
</div>
<div id="tabs-3">
<p>Bla bla</p>
</div>
instead of
<div id="tabs-1">
<table id="list1"><tr><td/></tr></table>
<div id="pager1"></div>
</div>
<div id="tabs-2">
<table id="list"><tr><td/></tr></table>
<div id="pager"></div>
</div>
<div id="tabs-3">
<p>Bla bla</p>
</div>
I modified you code a little to the following
jQuery(document).ready(function () {
var initGrids= [false,false];
$('#tabs').tabs({
show: function (event, ui) {
if (ui.index === 0 && initGrids[ui.index] === false) {
jQuery("#list1").jqGrid({
url: 'fillgrid.php',
datatype: 'json',
mtype: 'GET',
colNames: ['serial', 'type', 'origin', 'subtype', 'refreshdate'],
colModel: [
{ name: 'id', index: 'id', width: 55 },
{ name: 'type', index: 'type', width: 90 },
{ name: 'origin', index: 'origin', width: 80, align: 'right' },
{ name: 'subtype', index: 'subtype', width: 80, align: 'right' },
{ name: 'refreshdate', index: 'refreshdate', width: 80, align: 'right' }
],
pager: '#pager1',
rowNum: 10,
rowlist: [10, 20, 30],
sortname: 'id', // NOT 'serial',
sortorder: 'desc',
viewrecords: true,
caption: 'CPE Items',
width: 950
});
jQuery("#list1").jqGrid('navGrid', '#pager1', { edit: false, add: false, del: false });
initGrids[ui.index] = true;
}
else if (ui.index === 1 && initGrids[ui.index] === false) {
$("#list").jqGrid({
url: 'fillgridwo.php',
datatype: 'json',
mtype: 'GET',
colNames: ['Job Number', 'Date', 'System', 'Status', 'Technician', 'Timeframe'],
colModel: [
{ name: 'id', index: 'id', width: 55 },
{ name: 'Date', index: 'date', width: 90 },
{ name: 'System', index: 'wsystem', width: 80, align: 'right' },
{ name: 'Status', index: 'status', width: 80, align: 'right' },
{ name: 'Technician', index: 'wname', width: 80, align: 'right' },
{ name: 'Timeframe', index: 'time', width: 80, align: 'right' }
],
pager: '#pager',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id', // NOT 'jobno' or 'Job Number'
sortorder: 'desc',
viewrecords: true,
caption: 'Work Orders',
width: 950,
onSelectRow: function (id) {
//var d;
if (id) {
alert(id);
//??? onclick = openbox('Edit Work Order', 1);
//??? d = "jobno=" + id;
$.ajax({
url: 'fillwo.php',
type: 'POST',
dataType: 'json',
data: {jobno:id},
success: function (data) {
var id;
for (id in data) {
if (data.hasOwnProperty(id)) {
$(id).val(data[id]);
}
}
}
});
$("button, input:submit").button();
}
jQuery('#list').editRow(id, true);
}
});
jQuery("#list").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
initGrids[ui.index] = true;
}
else if (ui.index === 2) {
alert('tab2');
}
}
});
});
I included array initGrids which will be used to initialize every grid only once, commented unclear code like onclick = openbox('Edit Work Order', 1); and fixed sortname.
You can see the demo. The grid contain will be not filled, because I not have any server components on the server
I know its an old question. But I also faced the same issue where in I had multiple jqGrids under the tabs and the loading thing was not working.
Adding the below code in the javascript just before defining the grid worked for me:
$('#Grid').jqGrid('GridDestroy');
For me, the grids on different tabs where the same only the data inside the grid was changing.

Resources