How to enable excel export button for jqGrid - asp.net-mvc

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"
});

Related

Ext.Ajax.request not working

![
this is the project structure I am using. On adding a local URL like this below code is not working. url:'data/showStudentInfo.html']3I am using Ext Js version 4.1.1
In my application , I am having a grid, which uses a store.
On clicking "click me" button I want to redirect to the server, for test purpose I am using a basic google url,
But the class Ext.Ajax.Request is not working I think
Please help , as I am new to Ext js, I am not aware of the mistake I am making.
I am trying this in notepad++, as well as in eclipse ide (indigo version).
both with same output, Ext.Ajax.Request part not working.
It will of great help if anyone have suggestion as if I want to send
Thanking in advance
Below is my html and js file
practiseCellEditEx.js
Ext.require([
'Ext.data.*',
'Ext.Ajax.',
'Ext.grid.*'
]);
function getRandomDate() {
var from = new Date(1900, 0, 1).getTime();
var to = new Date().getTime();
var date = new Date(from + Math.random() * (to - from));
return Ext.Date.clearTime(date);
}
function createFakeData(count) {
var firstNames = ['Ed', 'Tommy', 'Aaron', 'Abe'];
var lastNames = ['Spencer', 'Maintz', 'Conran', 'Elias'];
var data = [];
for (var i = 0; i < count ; i++) {
var dob = getRandomDate();
var firstNameId = Math.floor(Math.random() * firstNames.length);
var lastNameId = Math.floor(Math.random() * lastNames.length);
var name = Ext.String.format("{0} {1}", firstNames[firstNameId], lastNames[lastNameId]);
data.push([name, dob]);
}
return data;
}
Ext.onReady(function(){
Ext.define('Person',{
extend: 'Ext.data.Model',
fields: ['Name', 'dob']
});
var store = Ext.create('Ext.data.Store', {
model: 'Person',
autoLoad: true,
proxy: {
type: 'memory',
data: createFakeData(10),
reader: {type: 'array'}
},
sorters: [{
direction:'ASC'
}]
});
Ext.create('Ext.grid.Panel', {
store: store,
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit : 1
})
],
columns: [
{
text: "Name",
width:120,
dataIndex: 'Name',
editor : {
xtype: 'textfield',
allowBlank:false
}
},
{
text: "DOB",
width: 120,
dataIndex: 'dob',
renderer: Ext.util.Format.dateRenderer('M d, Y'),
editor: {
xtype: 'datefield',
format: 'M d, Y',
minValue: '01/01/1900',
maxValue: new Date()
}
},
{
xtype: 'actioncolumn',
width: 30,
sortable: false,
menuDisabled: true,
items: [{
icon: 'http://etf-prod-projects-1415177589.us-east-1.elb.amazonaws.com/trac/docasu/export/2/trunk/client/extjs/shared/icons/fam/delete.gif',
handler: function(grid, rowIndex, colIndex) {
store.removeAt(rowIndex);
}
}]
}
],
renderTo:'example-grid',
width: 280,
height: 280
});
Ext.create('Ext.Button', {
text: 'Click me',
// renderTo: Ext.getBody(),
renderTo:'myBtn',
handler: getName
});
function getName (btn)
{
alert("hello");
var records = store.getAt(1);
alert('the name at index 1 is:'+records.get('Name'));
Ext.Ajax.request({
url : 'https://www.google.co.in/'
});
};
/*
function buttonClicked() {
Ext.MessageBox.confirm( 'Delete this part ? :' );
}*/
});
practiseCellEditEx.html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>ExtJS Samples</title>
<link rel="stylesheet" type="text/css" href="../resources/css/ext-all.css" />
<script type="text/javascript" src="../adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../ext-all.js"></script>
<script type="text/javascript" src="practiseCellEditEx.js"></script>
</head>
<body>
<h2> <b>Helllo , today's Date is 02.12.2015 </b></h2>
<div id="example-grid"></div>
<!--<button id="myBtn"></button>-->
<div id="myBtn"></div>
</body>
</html>
The problems seems to be simply the request going to google.com. In my browser it is blocked because it is a cross-origin request (an ajax request to another domain), see also here for further information: https://en.wikipedia.org/wiki/Same-origin_policy.
The same code with a request to a local URL works fine.

How to bind grid dynamically in ext.net mvc?

I am very new in ext.net mvc. I have problem of binding grid in ext.net mvc.
My code as below. I checked service return json data. But not show any data in grid view. Any missing in my code.
How to bind json data in grid? Please advice me any other ways. I have not found many sample in online regarding ext.net mvc.
#{
ViewBag.Title = "A Task";
//Layout = "~/Views/Shared/_BaseLayout.cshtml";
}
<script type="text/javascript" src="http://extjs-public.googlecode.com/svn/tags/ext-2.2/release/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="http://extjs-public.googlecode.com/svn/tags/ext-2.2/release/ext-all.js"></script>
<script type="text/javascript">
Ext.onReady(function () {
var store = new Ext.data.JsonStore({
url: 'http://localhost:49813/Areas/ASample/WcfService/AService.svc/GetDatas',
root: 'GetDatas',
idProperty: 'Id',
fields: ['Id', 'Employee_Name'],
remoteSort: true,
autoLoad: true
});
var cm = new Ext.grid.ColumnModel({
columns: [
{ header: 'Id', dataIndex: 'Id', hidden: true },
{ header: 'Employee Name', dataIndex: 'Employee_Name', width: 100 }
],
defaults: {
sortable: true,
scope: this,
menuDisabled: true,
align: 'left'
}
});
alert(1);
var grid = new Ext.grid.GridPanel({
title: 'Employees',
store: store,
colModel: cm,
renderTo: Ext.get('divGrid'),
width: 500,
height: 350,
border: true,
loadMask: true
});
});
</script>
<h2>A Task</h2>
Loading the store is async, so who says if the store is loaded? Try listen to the store.load event and from there do a reconfigure on the grid.
You can also set autoLoad to false and manually load the store.

Kendo UI Grid custom sorting

I have a grid in my application where the user wants the following functionality.
Scenerio
There are 4 columns in the grid, let's call them A, B, C and D.
Multiple columns are sortable and can be reordered.
The default sort is column A, B, C, D
If the user drags column C to be the first column, then the sort should be C, A, B, D.
I know there's a columnOrder event on the grid. Is this functionality possible? Is there an example anywhere or could someone give me direction on how to accomplish this functionality?
Thanks
Jim
In the event handler you can get the new column order from: this.columns. Then you should compose the sorting criteria and apply it.
Something like:
columnReorder: function() {
var sort = [];
$.each(this.columns, function(idx, elem) {
// In my case order by those columns that start with "Ship"
if (elem.field.lastIndexOf("Ship", 0) === 0) {
sort.push({field: elem.field, dir: "asc"});
}
});
this.dataSource.sort(sort);
},
Following a runnable example.
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
ShipCountry: { type: "string" },
ShipCity: { type: "string" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShippedDate: {type: "date" }
}
}
},
pageSize: 15
},
height: 550,
sortable: true,
reorderable: true,
resizable: true,
pageable: true,
columnReorder: function() {
var sort = [];
$.each(this.columns, function(idx, elem) {
if (elem.field.lastIndexOf("Ship", 0) === 0) {
sort.push({field: elem.field, dir: "asc"});
}
});
this.dataSource.sort(sort);
},
columns: [
{
field: "OrderID",
title: "ID",
width: 80
},
{
field: "ShipCity",
title: "Ship City"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShippedDate",
title: "Shipped Date",
format: "{0:MM/dd/yyyy}",
width: 200
}
]
});
});
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.2.624/styles/kendo.common-office365.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.2.624/styles/kendo.office365.min.css" />
<script src="http://cdn.kendostatic.com/2015.2.624/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.2.624/js/kendo.all.min.js"></script>
<div id="grid"></div>

ASP.net Mvc 2.0 with JQGrid

I have to implement inline editing with combobox in JQGrid,and i have to populate data in combobox from database no hard coded value i have already written the view part and i am using Linq to Sql as model but not able to write controller for that. I have got one sample for that but in sample repository design pattern has been used and i have not to use that.So can any on help me to write thebcontroller part.
My view part is
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<link href="../../Content/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" type="text/css" />
<link href="../../Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/JQGrid/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="../../Scripts/JQGrid/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="../../Scripts/JQGrid/jquery.jqGrid.src.js" type="text/javascript"></script>
<script src="../../Scripts/JQGrid/grid.locale-en.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Grid").jqGrid(
{ url: '/Default/GetData',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'UserName', 'Organization', 'Report Type', 'EmailID', 'Action'],
colModel: [
{ name: 'Id', index: 'Id', align: 'center', width: 30, editable: false },
{ name: 'UserName', index: 'UserName', align: 'center', width: 150, editable: true, edittype: 'select', formatter: 'select', editoptions: { dataUrl: '/Default/UserSelect' } },
{ name: 'Organization', index: 'Organization', align: 'center', width: 200, editable: true, edittype: 'select', formatter: 'select', editoptions: { dataUrl: '/Default/OrganizationSelect' }, editrules: { required: true} },
{ name: 'Report Type', index: 'Report Type', align: 'center', width: 200, editable: true, edittype: 'select', editoptions: { value: 'MN:Monthly; YR:Yearly', defaultValue: 'Montyhly'} },
{ name: 'EmailID', index: 'EmailID', align: 'center', width: 250, editable: true, edittype: 'text', editoptions: { size: 30, maxlength: 40} },
{ name: 'act', width: 100, align: 'center', sortable: false, formatter: 'actions', formatoptions: { keys: true, editbutton: true}}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "asc",
viewrecords: true,
caption: 'Regen Users'
});
});
</script>
<title>Index</title>
</head>
<body>
<div>
<table id="Grid">
</table>
</div>
<div id="pager">
</div>
</body>
</html>
And my get data controller is as
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Important.Models;
using System.Linq.Dynamic;
namespace Important.Controllers
{
public class DefaultController : Controller
{
RegenDataContext db = null;
public DefaultController()
{
db = new RegenDataContext();
}
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult GetData(string sidx, string sord, int page, int rows)
{
var pageIndex = Convert.ToInt32(page) - 1;
var pageSize = rows;
var totalRecords = db.rptUsers.Count();
var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
var user = db.rptUsers
.OrderBy(sidx + " " + sord)
.Skip(pageIndex * pageSize)
.Take(pageSize).AsQueryable();
var jsonData = new
{
rows = (
from rptUser u in user
select new
{
i=u.ID,
cell=new string[]{u.ID.ToString(),u.UserName, u.UserOrganizationID.ToString()}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
public ActionResult UserSelect()
{
return View();
}
public ActionResult OrganizationSelect()
{
return View();
}
}
}
help me to write controller action for data url UserSelect.
As per below jqGrid documentation
Setting the editoptions dataUrl parameter: The editoptions dataUrl parameter is valid only for element of edittype:select. The dataUrl parameter represent the url from where the html select element should be get.
When this option is set, the element will be filled with values from the AJAX request. The data should be a valid HTML select element with the desired options - something like:
<select>
<option value='1'>One</option>
<option value='2'>Two</option>
...
</select>
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules#edittype
something like below: NOT TESTED
public JsonResult UserSelect()
{
List<User> users=db.GetUsers();
return Json(users,JsonRequestBehavior.AllowGet);
}
View: jqGrid
editoptions: { dataUrl:'<%= Url.Action("xxxx","xxxx") %>',
buildSelect: function(data) {
var response = jQuery.parseJSON(data.responseText);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l=response.length; i<l ; i++) {
var ri = response[i];
s += '<option value="'+ri+'">'+ri+'</option>';
}
}
return s + "</select>";
}
}
Check this:
ASP.NET MVC $.post call returning string...need help with format for jqGrid

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;
}

Resources