Ext.Ajax.request not working - url

![
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.

Related

highmaps stopped updating after move to .NET Core

I have a working website using the standard Visual Studio 2017. It is composed of a C# backend with a single API used to request data to be displayed in HighMaps based on the settings the user chooses from the jQuery UI. Since I don't love my Windows machine nearly as much as my Mac, I thought I would try using .Net Core 2.0 - and thus eliminate the need for my Windows laptop. Everything went extremely well (Kudos to Microsoft), but for some reason the jQuery code that calls the API, the data returned is not being pushed into the map like it should.
Here is the jQuery code that runs - the alert() does display the JSON data, but it never is reflected in the map. I can post HTML or CSS if needed, but for now I have included the head and script sections.
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Great Locations</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/maps/highmaps.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/maps/modules/data.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/mapdata/countries/us/us-all-all.js"></script>
</head>
And here is the jQuery Code:
<script type="text/javascript">
var climateSteps = [
"Tropical",
"Semi-Arid",
"Desert",
"Humid",
"Mediterranean",
"Wet All Seasons",
"Wet Summer",
"Winter Snow",
"Polar"];
var climateRange = "C08";
$(function () {
$("#climate-slider .slider").slider({
range: true,
min: 0,
max: 8,
values: [0, 8],
slide: function (event, ui) {
climateRange = "C" + ui.values[0].toString() + ui.values[1].toString();
if (ui.values[0] == ui.values[1]) {
/* if user selected a single value (not a range), adjust text to fit */
$(this).parent().children(".slider-range").text(climateSteps[ui.values[0]]);
}
else {
$(this).parent().children(".slider-range").text(climateSteps[ui.values[0]] + " to " + climateSteps[ui.values[1]]);
}
}
})
});
$.noConflict();
tableResult = '[{"code":"us-al-001","name":"Autauga County, AL","value":1}, {"code":"us-il-019","name":"Champaign County, IL","value":3}]';
(function ($) {
function GetCounties(userSelections) {
jQuery.support.cors = true;
$.ajax({
url: "http://localhost:5000/api/products/" + userSelections,
type: "GET",
dataType: "json",
success: function (d) {
data = JSON.stringify(d);
alert("API data received: " + data)
tableResult = data;
$("#map-container").highcharts().series[0].update({
data: JSON.parse(d)
});
},
error: function (d) {
alert("API found error: " + JSON.stringify(d));
}
});
}
jQuery(".button-submit").bind("click", {
}, function (e) {
GetCounties(climateRange);
});
data = JSON.parse(tableResult);
var countiesMap = Highcharts.geojson(Highcharts.maps["countries/us/us-all-all"]);
var lines = Highcharts.geojson(Highcharts.maps["countries/us/us-all-all"], "mapline");
// add state acronym for tooltip
Highcharts.each(countiesMap, function (mapPoint) {
var state = mapPoint.properties["hc-key"].substring(3, 5);
mapPoint.name = mapPoint.name + ", " + state.toUpperCase();
});
var options = {
chart: {
borderWidth: 1,
marginRight: 50 // for the legend
},
exporting: {
enabled: false
},
title: {
text: "My Great Locations"
},
legend: {
layout: "vertical",
align: "right",
floating: true,
valueDecimals: 0,
valueSuffix: "",
backgroundColor: "white",
symbolRadius: 0,
symbolHeight: 0
},
mapNavigation: {
enabled: false
},
colorAxis: {
dataClasses: [{
from: 1,
to: 1,
color: "#000099",
name: "Perfect!"
}, {
from: 2,
to: 2,
color: "#009999",
name: "Very Nice!"
}, {
from: 3,
to: 3,
color: "#00994c",
name: "Good Fit"
}]
},
tooltip: {
headerFormat: "",
formatter: function () {
str = "Error";
if (this.point.value == 1) {
str = "Perfect!";
}
if (this.point.value == 2) {
str = "Very Nice!";
}
if (this.point.value == 3) {
str = "Good Fit";
}
return this.point.name + ": <b>" + str + "</b>";
}
},
plotOptions: {
mapline: {
showInLegend: false,
enableMouseTracking: false
}
},
series: [{
mapData: countiesMap,
data: data,
joinBy: ["hc-key", "code"],
borderWidth: 1,
states: {
hover: {
color: "#331900"
}
}
}, {
type: "mapline",
name: "State borders",
data: [lines[0]],
color: "black"
}]
};
// Instanciate the map
$("#map-container").highcharts("Map", options);
All that appears in the map are the two counties that I hardcoded (to show that the map is working fine). I'm wondering if there is some package I need to add into NuGet or SDK Dependencies, but so much is working that I don't know what is missing. And I've not figured out how to show the console in Mac Visual Studio, so if any clues are going there, I haven't seen them.
Great thanks to the Highcharts support team - the ultimate answer to this problem is that the Mac Visual Studio .Net Core framework for some reason acts different than the Windows platform running the classic Visual Studio. Here is the answer that worked for me:
I needed to use this with Mac Visual Studio with .Net Core - no JSON.parse(d) required:
$("#map-container").highcharts().series[0].update({
data: d
});
Instead of this, which works for Windows full-blown Visual Studio (community edition):
$("#map-container").highcharts().series[0].update({
data: JSON.parse(d)
});

Graph in popup and separate Div in Leaflet

I wonder if anyone can tell me what is wrong in my code please? I want to be able to select a polygon and show a graph in a popup using leaflet and highchart. I have managed to create the graph in the popup, but the line is missing on it, and I also get a separate div showing the same chart (and the line) at the bottom of my web page which I don't want. Can anyone tell me how to get the line to show on the chart in the popup and to remove the separate chart? Here is my code.enter code here
<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--include leaflet CSS file-->
<link rel="stylesheet" href="css/leaflet.css" />
<link rel="markers" type="images/marker-icon" href="images/marker-icon.png" />
<!--include Leaflet Javascript file-->
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="js/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script src='http://unpkg.com/leaflet#1.0.2/dist/leaflet.js'></script>
<script src="js/esri-leaflet.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
</head>
<body>
<!--Put a div element with a certain id where you want your map to be: -->
<div id="map" style="width: 1000px; height: 800px;"></div>
<div id="chartcontainer" class="highchart" style="width: 500px; height: 200px;"></div>
<!-- First we’ll initialize the map and set its view to our chosen geographical coordinates and a zoom level:-->
<script>
var mymap = L.map('map', {
zoomControl:true, maxZoom:28, minZoom:1
}).fitBounds([[51.0269253989,-1.34762355597],[51.1990603009,-0.951310026203]]);
L.esri.basemapLayer('Imagery').addTo(mymap);
//loads geoserver layer as WMS
var field_boundaries = L.tileLayer.wms("http://localhost:1997/geoserver/RSAC/wms", {
layers: 'RSAC:results_clipped_with_growth_small_new',
format: 'image/png',
transparent: true,
version: '1.1.0',
attribution: "myattribution"
});
//loads the geojson layer
var owsrootUrl = 'http://localhost:1997/geoserver/RSAC/wms';
var defaultParameters = {
service : 'WFS',
version : '2.0',
request : 'GetFeature',
typeName : 'RSAC:results_clipped_with_growth_small_new',
outputFormat : 'json',
format_options : 'callback:getJson',
SrsName : 'EPSG:4326'
};
var parameters = L.Util.extend(defaultParameters);
var URL = owsrootUrl + L.Util.getParamString(parameters);
var ajax = $.ajax({
url : URL,
dataType : 'json',
jsonpCallback : 'getJson',
success : function (response) {
L.geoJson(response, {
onEachFeature: function (feature, url) {
url.on('click', function(e){
var chartplotoptions ={
chart: {
type: 'line'
},
title: {
text: 'Growth'
},
xAxis: {
allowDecimals: true,
categories: ['20151114', '20151126', '20151208', '20151220', '20160113', '20160125', '20160206', '20160218', '20160301', '20160313', '20160325', '20160406', '20160418', '20160430', '20160512', '20160524', '20160605', '20160629', '20160723', '20160804', '20160816'],
labels: {
formatter: function () {
return this.value;
}
}
},
yAxis: {
startOnTick: false,
minPadding: 0.05,
title: {
text: 'Crop Growth',
},
labels: {
formatter: function () {
return this.value;
}
}
},
tooltip: {
pointFormat: '{series.name}{point.y}'
},
plotOptions: {
area: {
pointStart: -20,
threshold: 10,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: false
}
}
}
}
},
series: [{
name: 'Growth',
data: [parseFloat(feature.properties.Date_20151114),parseFloat(feature.properties.Date_20151126),parseFloat(feature.properties.Date_20151208), parseFloat(feature.properties.Date_20151220), parseFloat(feature.properties.Date_20160113), parseFloat(feature.properties.Date_20150125), parseFloat(feature.properties.Date_20160206), parseFloat(feature.properties.Date_20160218), parseFloat(feature.properties.Date_20160301), parseFloat(feature.properties.Date_20160313), parseFloat(feature.properties.Date_20160325), parseFloat(feature.properties.Date_20160406), parseFloat(feature.properties.Date_20160418), parseFloat(feature.properties.Date_20160430), parseFloat(feature.properties.Date_20160512), parseFloat(feature.properties.Date_20160524), parseFloat(feature.properties.Date_20160605), parseFloat(feature.properties.Date_20160629), parseFloat(feature.properties.Date_20160723), parseFloat(feature.properties.Date_20160804), parseFloat(feature.properties.Date_20160816)]
},
]
};
$('#chartcontainer').highcharts(chartplotoptions);
url.bindPopup($('#chartcontainer').html());
url.openPopup();
});
}
}).addTo(mymap);
}
});
</script>
</body>
</html>
You don't need the div element in your HTML markup. You can create one on the fly in your onEachFeature function and add it to the popup. Also, you need to initialize your highchart after the popup has opened, not before. In code with comments:
new L.GeoJSON(feature, {
onEachFeature: function (feature, layer) {
// Create div with class name highchart
var div = L.DomUtil.create('div', 'highchart');
// Bind popup to layer with div as content
layer.bindPopup(div);
// Handle event when popup opens
layer.on('popupopen', function (e) {
console.log(e.target); // layer object
console.log(e.target.feature); // layer's feature object
console.log(e.popup); // popup object
console.log(e.popup.getContent()); // the div
// Now do the highcharts stuff
Highcharts.chart(e.popup.getContent(), { /**/ });
});
}
});
And don't forget to set the div's dimensions with CSS:
.highchart {
width: 500px;
height: 200px;
}

How do I build a grid of PortfolioItem/Features with associated User Stories that have no children?

I want to create a custom grid on My Dashboard of User Stories under a portfolio item without child stories.
A custom grid on My Dashboard with Object: PortfolioIetm Feature and query UserStories.DirectChildrenCount = 0
it will produce this error:
Could not parse: Attribute "UserStories" on type PortfolioItems is not allowed in query expressions.
Here is a custom App SDK 2 app that builds a grid of Features with user stories where DirectChildrenCount = 0. It accesses the collection of stories on every feature
var stories = feature.getCollection('UserStories');
but populates the grid only with those stories that have no children. Here is the full App.html code that can be pasted into a custom tab:
<!DOCTYPE html>
<html>
<head>
<title>GridExample</title>
<script type="text/javascript" src="/apps/2.0rc1/sdk.js"></script>
<script type="text/javascript">
Rally.onReady(function () {
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
Ext.create('Rally.data.WsapiDataStore', {
model: 'PortfolioItem/Feature',
fetch: ['FormattedID','Name','UserStories'],
pageSize: 100,
autoLoad: true,
listeners: {
load: this._onDataLoaded,
scope: this
}
});
},
_createGrid: function(features) {
this.add({
xtype: 'rallygrid',
store: Ext.create('Rally.data.custom.Store', {
data: features,
pageSize: 100
}),
columnCfgs: [
{
text: 'Formatted ID', dataIndex: 'FormattedID', xtype: 'templatecolumn',
tpl: Ext.create('Rally.ui.renderer.template.FormattedIDTemplate')
},
{
text: 'Name', dataIndex: 'Name'
},
{
text: 'Story Count', dataIndex: 'StoryCount'
},
{
text: 'User Stories', dataIndex: 'UserStories',
renderer: function(value) {
var html = [];
Ext.Array.each(value, function(userstory){
html.push('' + userstory.FormattedID + '')
});
return html.join(', ');
}
}
]
});
},
_onDataLoaded: function(store, data){
var features = [];
var pendingstories = data.length;
//debugger;
Ext.Array.each(data, function(feature) {
var f = {
FormattedID: feature.get('FormattedID'),
Name: feature.get('Name'),
_ref: feature.get("_ref"),
StoryCount: feature.get('UserStories').Count,
UserStories: []
};
var stories = feature.getCollection('UserStories');
stories.load({
fetch: ['FormattedID'],
callback: function(records, operation, success){
Ext.Array.each(records, function(story){
var number = story.get('DirectChildrenCount');
if (number == 0) {
f.UserStories.push({_ref: story.get('_ref'),
FormattedID: story.get('FormattedID')
});}
}, this);
--pendingstories;
if (pendingstories === 0) {
this._createGrid(features);
}
},
scope: this
});
features.push(f);
}, this);
}
});
Rally.launchApp('CustomApp', {
name:"GridExample"
//parentRepos:""
});
});
</script>
<style type="text/css">
.app {
/* Add app styles here */
}
</style>
</head>
<body></body>
</html>

Hyperlinks in Dojo Tree

There is an example tree in the dojo campus with hyperlinks. They are not clickable. Does anyone have a dojo implementation with clickable links? Have you been able to determine which node/link was clicked? I am looking for sample code that does this.
Here is the sample code from dojo campus. How do I make these links clickable and how do I implement node selection from click of image?
Thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr">
<head>
<style type="text/css">
body, html { font-family:helvetica,arial,sans-serif; font-size:90%; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
djConfig="parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.Tree");
var rawdata = [{
label: 'Something <b>important</b>',
id: '1',
children: [{
label: 'Life',
id: '1.1'
},
{
label: 'Liberty',
id: '1.2'
}]
},
{
label: 'Some links (note: the link is <b>not</b> clickable)',
id: '2',
children: [{
id: '2.1',
label: 'Dojo Toolkit'
},
{
id: '2.2',
label: '<img src="http://dojofoundation.org/media/img/dojo.logo.png" alt="greatest ever" height="32px" />'
},
{
id: '2.3',
label: 'my blog'
}]
}];
function prepare() {
var store = new dojo.data.ItemFileReadStore({
data: {
identifier: 'id',
label: 'label',
items: rawdata
}
});
var treeModel = new dijit.tree.ForestStoreModel({
store: store
});
var treeControl = new dijit.Tree({
model: treeModel,
showRoot: false,
_createTreeNode: function(
/*Object*/
args) {
var tnode = new dijit._TreeNode(args);
tnode.labelNode.innerHTML = args.label;
return tnode;
}
},
"treeOne");
}
dojo.addOnLoad(prepare);
</script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css"
/>
</head>
<body class=" claro ">
<div id="treeOne">
</div>
<!-- NOTE: the following script tag is not intended for usage in real
world!! it is part of the CodeGlass and you should just remove it when
you use the code -->
<script type="text/javascript">
dojo.addOnLoad(function() {
if (document.pub) {
document.pub();
}
});
</script>
</body>
</html>
You can do a connect to the onClick event on the Tree. When creating your Tree, add an extra onClick parameter to your constructor, pointing to a function with the following signature:
function myOnClickHandler(item, tree, evt){
//item is the node's DataStore item
//I forgot if tree is the whole tree or just the currtent node
//evt is the usual event object, with things like mouse position, etc...
console.log('clicked a tree');
}
var treeControl = new dijit.Tree({
model: treeModel,
showRoot: false,
_createTreeNode: function( /*Object*/ args) {
var tnode = new dijit._TreeNode(args);
tnode.labelNode.innerHTML = args.label;
return tnode;
},
onClick: myOnclickHandler // THIS LINE //
},
"treeOne");

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

Resources