I am new to knockout and MVC. I wanted to add a link button(delete) which will delete the record that is displayed in my knockout grid. I really dont have any idea how to achieve this. I have the following code that displays the record using the KO grid. Now I want to add a link button in the grid to delete the record
CONTROLLER:
public JsonResult GetResult()
{
GetResultRequest req = new GetResultRequest() { AcctID=57345, PartyType=2 };
var getResultInfo = WSHelper.WsService.GetResults(req);
return Json(getResultInfo.Signers, JsonRequestBehavior.AllowGet);
}
VIEW:
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/SafeHarborBundle")
<script src="~/Scripts/koGrid-2.1.1.js"></script>
<script type="text/javascript">
var dataViewModel = ko.mapping.fromJS(#Html.Raw(Json.Encode(Model)));
<div id="gridSigner">
<div id="grids123" style="height: 700px; width: 650px;"
data-bind="koGrid: {
data: gridItems, columnDefs: [{ field: 'AcctID', displayName: 'AcctID', width: '150' },
{ field: 'FName', displayName: 'First Name', width: '150' },
{ field: 'LName', displayName: 'Last Name', width: '150' },
{ field: 'AliasFName', displayName: 'Alias First Name', width: '150' },
{ field: 'SSN', displayName: 'AcctID', width: '150' }],
autogenerateColumns: false,
isMultiSelect: false,
showFilter: true,
showColumnMenu: true,
enablePaging: false,
displaySelectionCheckbox: false,
enableColumnResize: false,
multiSelect: false
}">
JQUERY FILE:
$(document).ready(function () {
loadApplication(dataViewModel);
ko.applyBindings(Gridviews, document.getElementById('gridSigner'));
});
function loadApplication(initialData) {
self = this;
self.ViewModel = initialData;
self.BranchOptions = ko.observableArray([]);
self.AcctTypeOptions = ko.observableArray([]);
self.OriginationOptions = ko.observableArray([]);
self.Message = ko.observable();
SearchSignerData();
ko.applyBindings(self, document.getElementById('main-search'));
}
SearchSignerData = function () {
$.ajax({
type: "Get",
url: "/SafeHarborApp/GetResult",
contentType: 'application/json',
async: true,
cache: false,
beforeSend: function () {
},
success: function (result) {
alert(result[0].AcctID.toString());
if (result.length != 0) {
$.each(result, function (i, item) {
Gridviews.gridItems.push(item);
});
}
else {
Gridviews.gridItems.removeAll();
alert("No Records found");
}
},
complete: function () {
},
error: function (xhr, textStatus, errorThrown) {
//alert(jqXHR.responseText);
var title = xhr.responseText.split("<title>")[1].split("</title>")[0];
alert(title);
// Handle error.
}
});
}
The above code works fine in displaying the record in the KO grid. However, I dont know how to add a delete button in the displayed KO grid now. I tried searching for it but was not able to find anything useful that will get me the result. Please help...
Use CellTemplate in ko grid.plese see code below
<script type="text/javascript">
self.NoOfAccountColumn = '<a data-bind="value: $parent.entity" onclick="Popup(this.value)">No Of Account</a>';
self.Delete = '<a data-bind="value: $parent.entity" onclick="deleteRow(this.value)">Delete</a>';
function Popup(rowItem) {
alert(rowItem.AffinityNum + ' ' + rowItem.ClientName + ' : NoOfAccount Clicked');
}
function deleteRow(rowItem) {
alert(rowItem.AffinityNum + ' ' + rowItem.ClientName + ' : Delete Clicked');
}
function isDoubleClick(oldValue, currentValue) {
var responseTime = 400;
if ((currentValue - oldValue) <= responseTime) {
self.clickTime = currentValue;
return true;
}
self.clickTime = currentValue;
return false;
};
</script>
<script src="~/Scripts/Packages/koGrid-2.1.1.js"></script>
<div id="disp">
<div id="grid" style="height: 200px; width: 600px"
data-bind="koGrid: {
data: BranchOptions,
afterSelectionChange: function (rowItem, event) {
if (event.type == 'click' && isDoubleClick(self.clickTime, event.timeStamp)) {
alert(rowItem.entity.ClientName + ' : Row DoubleClick');
}
},
columnDefs: [{ field: 'ClientName', displayName: 'Client Name', width: '*', },
{ field: 'AffinityNum', displayName: 'Affinity Num', width: '*', cellTemplate: NoOfAccountColumn },
{ field: 'AffinityID', displayName: 'Affinity ID', width: '*', cellTemplate: Delete }],
autogenerateColumns: false,
isMultiSelect: false,
showFilter: true,
showColumnMenu: true,
enablePaging: false,
displaySelectionCheckbox: false,
enableColumnResize: true,
multiSelect: false
}">
</div>
</div>
Related
I'm trying to use the Drilldown in Map (vue-Highchart), but cannot get it working.
like this: https://www.highcharts.com/maps/demo/map-drilldown
Anyone have any examples of this in Vue.js? Please.
Tks.
Here is simple example of drilldown functionality(with vue-highcharts) which provides drilldown and drillup event from Vue-instance:
Vue.use(VueHighcharts, { Highcharts: Highcharts });
// helper script to load external script
let loadScript = function(url, onLoad){
var scriptTag = document.createElement('script');
scriptTag.src = url;
scriptTag.onload = onLoad;
scriptTag.onreadystatechange = onLoad;
document.body.appendChild(scriptTag);
};
// simple chart options
var options = {
chart: {},
title: {
text: 'Highcharts-Vue Map Drilldown Example'
},
subtitle: {
text: '',
floating: true,
align: 'right',
y: 50,
style: {
fontSize: '16px'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
colorAxis: {
min: 0,
minColor: '#E6E7E8',
maxColor: '#005645'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
plotOptions: {
map: {
states: {
hover: {
color: '#EEDD66'
}
}
}
},
drilldown: {
activeDataLabelStyle: {
color: '#FFFFFF',
textDecoration: 'none',
textOutline: '1px #000000'
},
drillUpButton: {
relativeTo: 'plotBox',
position: {
x: 70,
y: 280
}
}
},
series: [{
data: Highcharts.geojson(Highcharts.maps['countries/us/us-all']).map((d, i) => {
d.drilldown = true;
// set value just for example
d.value = i;
return d;
}),
name: 'USA',
dataLabels: {
enabled: true,
format: '{point.properties.postal-code}'
}
}]
};
let vm = new Vue({
el: '#app',
data: {
isLoading: false,
options: options
},
created() {
// prepare events for chart from Vue instance
this.options.chart.events = {
drilldown: this.drilldown.bind(this),
drillup: this.drillup.bind(this)
}
},
methods: {
drilldown(e) {
let { chart } = this.$refs.highcharts;
if (!e.seriesOptions) {
mapKey = 'countries/us/' + e.point.properties['hc-key'] + '-all';
if (Highcharts.maps[mapKey]) {
this.prepareDrilldownData(mapKey, e.point);
return;
}
this.isLoading = true;
loadScript('https://code.highcharts.com/mapdata/' + mapKey + '.js', () => {
this.isLoading = false;
this.prepareDrilldownData(mapKey, e.point);
});
}
chart.setTitle(null, { text: e.point.name });
},
drillup(e) {
let { chart } = this.$refs.highcharts;
chart.setTitle(null, { text: '' });
},
prepareDrilldownData(mapKey, point) {
let { chart } = this.$refs.highcharts;
data = Highcharts.geojson(Highcharts.maps[mapKey]).map((d, i) => {
// set value just for example
d.value = i;
return d;
});
chart.addSeriesAsDrilldown(point, {
name: point.name,
data: data,
dataLabels: {
enabled: true,
format: '{point.name}'
}
});
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<script src="https://code.highcharts.com/maps/highmaps.js"></script>
<script src="https://code.highcharts.com/maps/modules/drilldown.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-highcharts/dist/vue-highcharts.min.js"></script>
<script src="https://code.highcharts.com/mapdata/countries/us/us-all.js"></script>
<div id="app">
<highmaps ref="highcharts" :options="options"></highmaps>
<div v-if="isLoading" style="text-align: center; margin-top: 15px; font-size: 20px;">Loading...</div>
</div>
There is also jsfiddle if you want.
I am creating a dynamic search bar that will filter a sidebar full of names based on user input. However, I am having trouble temporarily hiding and showing data based on the search bar's value on keyup. What is the best way to achieve this the "Vue way"?
On keyup, I want to filter through all of the this.people data and only show names that contain the value of the search input.
Below is what my code looks like
Vue.component('sidebar',{
props: ['people', 'tables'],
data: () => {
return {
fullName: ''
}
},
computed: {
computed() {
return [this.people, this.tables].join()
}
},
template:
`
<div id="sidebarContain" v-if="this.people">
<input id="sidebar-search" type="text" placeholder="Search..." #keydown="searchQuery">
<select id="sidebar-select" #change="sidebarChanged">
<option value="AZ">A-Z</option>
<option value="ZA">Z-A</option>
<option value="notAtTable">No Table</option>
<option value="Dean's Guest">Dean's Guest</option>
<option value="BOO | VIP">BOO | VIP</option>
</select>
<div v-for="person in people" :class="[{'checked-in': isCheckedIn(person)}, 'person']" :id="person.id" :style="calcRegColor(person)">
<span v-if="person.table_name">{{person.first_name + ' ' + person.last_name + ' - ' + person.table_name}}</span>
<span v-else>{{person.first_name + ' ' + person.last_name}}</span>
</div>
</div>
`,
methods: {
isCheckedIn(person) {
return person.reg_scan == null ? true : false;
},
isHidden(person)
{
console.log("here");
},
calcRegColor(person)
{
switch(person.registration_type)
{
case "Dean's Guest" :
return {
color: 'purple'
}
break;
case "BOO | VIP" :
return {
color: 'brown'
}
break;
case "Student" :
return {
color: 'green'
}
break;
case "Faculty":
case "Staff":
return {
color: 'blue'
}
break;
case "Alumni Club Leader":
return {
color: 'gold'
}
break;
case "Table Guest" :
return {
color: 'pink'
}
break;
default:
return {
color: 'black'
}
}
}
},
watch: {
computed() {
console.log("People and Tables Available");
}
}
});
var app = new Vue({
el: '#main',
data: {
tables: {},
people: [],
currentAlerts: [],
lastDismissed: []
},
methods: {
loadTables() {
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'users/getTableAssignments/' + event_id
}).done(data => {
this.tables = data;
});
},
loadPeople() {
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'users/getParticipants2/' + event_id
}).done(data => {
this.people = data;
this.sortSidebar(this.people);
});
},
loadCurrentAlerts() {
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'alerts/getAlerts/' + event_id
}).done(data => {
this.currentAlerts = data;
});
},
loadLastDismissed(num = 15)
{
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'alerts/getLastDismissed/' + event_id + '/' + num
}).done(data => {
this.lastDismissed = data;
});
},
setRefresh() {
setInterval(() => {
console.log("Getting People and Tables");
this.loadPeople();
this.loadTables();
}, 100000);
},
makeTablesDraggable() {
$(document).on("mouseenter", '.table', function(e){
var item = $(this);
//check if the item is already draggable
if (!item.is('.ui-draggable')) {
//make the item draggable
item.draggable({
start: (event, ui) => {
console.log($(this));
}
});
}
});
},
makePeopleDraggable() {
$(document).on("mouseenter", '.person', function(e){
var item = $(this);
//check if the item is already draggable
if (!item.is('.ui-draggable')) {
//make the item draggable
item.draggable({
appendTo: 'body',
containment: 'window',
scroll: false,
helper: 'clone',
start: (event, ui) => {
console.log($(this));
}
});
}
});
}
makeDroppable() {
$(document).on("mouseenter", ".dropzone, .table", function(e) {
$(this).droppable({
drop: function(ev, ui) {
console.log("Dropped in dropzone");
}
});
});
}
},
mounted() {
this.loadTables();
this.loadPeople();
this.loadCurrentAlerts();
this.loadLastDismissed();
this.setRefresh();
this.makeTablesDraggable();
this.makePeopleDraggable();
this.makeDroppable();
}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
</head>
<div id="app">
<sidebar :people="people" :tables="tables"></sidebar>
</div>
You can change the people property in sidebar into a computed property, which will be calculated based on user's input.
So change the sidebar code to
<div v-for="person in filteredPeople" :class="[{'checked-in': isCheckedIn(person)}, 'person']" :id="person.id" :style="calcRegColor(person)">
<span v-if="person.table_name">{{person.first_name + ' ' + person.last_name + ' - ' + person.table_name}}</span>
<span v-else>{{person.first_name + ' ' + person.last_name}}</span>
</div>
and add a computed property
computed: {
filteredPeople () {
// Logic to filter data
}
}
A foolish aproach that I use, without computed properties:
JS:
new Vue({
el: '#app',
data: {
list: [],
filteredList: []
},
mounted(){
this.filteredList = this.list
},
methods: {
filter(e){
if(e.target.value === '') this.filteredList = this.list
else {
this.filteredList = []
this.list.forEach(item=>{
if(list.name.includes(e.target.value)) this.filteredList.push(item)
})
}
}
}
})
The "name" property of list object can be changed to whatever property you want to look for.
HTML:
<input #keyup="filter" id="search" type="search" required>
I have a page with two jqGrids on it in different elements. When I first load the page, Firebug reports an ajax call to get the first 15 rows as expected, and the pager accurately shows the number of pages and the number of records. However, when I click the arrows on the pager, no ajax call is traced in Firebug, so I am pretty sure that something is not wired correctly. The odd thing is that I have other pages with only one jqGrid and paging works as expected. I have breakpoints in my controller (MVC4) and the initial load hits them just fine and all of the arguments are correct:
#region GetUnManagedMerchants
public JsonResult GetUnManagedMerchants(string id, string sidx, string sord, int page, int rows)
{
return GetSomeMerchants(id, false, sidx, sord, page, rows);
}
#endregion
Here is my script code:
$(document).ready(function () {
jQuery("#grdUnManaged").jqGrid({
url: '/Ajax/GetUnManagedMerchants/' + $('#UserInContext_UserId').val(),
datatype: 'json',
mType: 'GET',
colNames: ['', 'UnManaged Merchant', ''],
colModel: [
{ name: 'Manage', key: true, index: 'manage', width: 20, sortable: false, formatter: function () { return '<img src="#Url.Content("~/content/images/icons/merchant.png")" width="16" height="16" alt="Merchants" />'; } },
{ name: 'Name', index: 'name', width: 325 },
{ name: 'id', index: 'id', width: 0, hidden: true , key: true}
],
pager: '#grdUnManagedPager',
rowNum: 15,
width: 450,
height: 300,
viewrecords: true,
caption: 'Current UnManaged Merchants',
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol == 0) {
var merchantId = jQuery(this).getRowData(rowid)['id'];
var userId = $('#UserInContext_UserId').val();
ManageMerchant(userId, merchantId);
return true;
}
return false;
}
});
jQuery("#grdUnManaged").jqGrid('navGrid', '#grdUnManagedPager', { add: false, edit: false, del: false, search: false, refresh: true });
});
Please help me with what is missing! This is the last item I need to fix prior to finishing this project.
Thanks!
I have made the changes you suggest (Thanks) yet I still do NOT get an ajax call back when I click on the pager to see a subsequent page. I am re-posting my entire script with both grids.
<script type="text/javascript">
var buttonNames = {};
buttonNames[0] = 'Manage';
$(document).ready(function () {
jQuery('#currentUserHeader').html('<h3>Merchant Lists for ' + $('#UserInContext_Email').val() + '.</h3>');
jQuery("#grdManaged").jqGrid({
url: '/Ajax/GetManagedMerchants/' + $('#UserInContext_UserId').val(),
datatype: 'json',
mType: 'GET',
colNames: ['', 'Managed Merchant', ''],
colModel: [
{ name: 'Manage', index: 'Manage', width: 20, sortable: false, formatter: function () { return '<img src="#Url.Content("~/content/images/chevron.png")" width="16" height="16" alt="Merchants" />'; } },
{ name: 'Name', index: 'Name', width: 325 },
{ name: 'id', index: 'id', width: 0, hidden: true, key: true }
],
pager: '#grdManagedPager',
rowNum: 15,
width: 450,
height: 300,
viewrecords: true,
caption: 'Current Managed Merchants',
beforeRequest: function () {
var getUrl = '/Ajax/GetManagedMerchants/' + $('#UserInContext_UserId').val();
$('#grdManaged').setGridParam([{ url: getUrl }]);
},
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol == 0) {
var merchantId = jQuery(this).getRowData(rowid)['id'];
var userId = $('#UserInContext_UserId').val();
UnManageMerchant(userId, merchantId);
return true;
}
return false;
}
});
jQuery("#grdManaged").jqGrid('navGrid', '#grdManagedPager', { add: false, edit: false, del: false, search: false, refresh: true });
});
</script>
<script type="text/javascript">
$(document).ready(function () {
jQuery("#grdUnManaged").jqGrid({
url: '/Ajax/GetUnManagedMerchants/' + $('#UserInContext_UserId').val(),
datatype: 'json',
mType: 'GET',
colNames: ['', 'UnManaged Merchant', ''],
colModel: [
{ name: 'Manage', index: 'Manage', width: 20, sortable: false, formatter: function () { return '<img src="#Url.Content("~/content/images/chevron-left.png")" width="16" height="16" alt="Merchants" />'; } },
{ name: 'Name', index: 'Name', width: 325 },
{ name: 'id', index: 'id', width: 0, hidden: true , key: true}
],
pager: '#grdUnManagedPager',
rowNum: 15,
width: 450,
height: 300,
viewrecords: true,
caption: 'Current UnManaged Merchants',
beforeRequest: function () {
var getUrl = '/Ajax/GetUnManagedMerchants/' + $('#UserInContext_UserId').val();
$('#grdUnManaged').setGridParam([{ url: getUrl }]);
},
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol == 0) {
var merchantId = jQuery(this).getRowData(rowid)['id'];
var userId = $('#UserInContext_UserId').val();
ManageMerchant(userId, merchantId);
return true;
}
return false;
}
});
jQuery("#grdUnManaged").jqGrid('navGrid', '#grdUnManagedPager', { add: false, edit: false, del: false, search: false, refresh: true });
});
may be your jqgrid overrides each other,may be on click paging second jqgrid overrides some thig,,,
but hope this help..
http://www.codeproject.com/Articles/594150/MVC-Basic-Site-Step-4-jqGrid-In
i have a grid developed using kendo ui and asp.net mvc4 razor.in there i have used the html syntax for kendo grid instead of asp.net mvc.
this is the code of my grid
<div id="example" class="k-content">
<div id="batchgrid">
</div>
</div>
<script type="text/javascript" lang="javascript">
$("#batchGrid").click(function () {
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true} },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
UnitsInStock: { type: "number", validation: { min: 0, required: true} },
Discontinued: { type: "boolean" },
TotalStock: { type: "number" }
}
}
},
// group: {
// field: "UnitPrice", aggregates: [
// { field: "UnitPrice", aggregate: "sum" },
// { field: "TotalStock", aggregate: "sum" }
// ]
// },
aggregate: [{ field: "TotalStock", aggregate: "sum"}]
});
$("#batchgrid").kendoGrid({
dataSource: dataSource,
dataBound: onDataBound,
navigatable: true,
filterable: {
messages: {
and: "And",
or: "Or",
filter: "Apply filter",
clear: "Clear filter",
info: "Filter by"
},
extra: false, //do not show extra filters
operators: { // redefine the string operators
string: {
contains: "Contains",
doesnotcontain: "Doesn't contain",
startswith: "Starts With",
endswith: "Ends"
},
number: {
eq: "Is Equal To",
neq: "Not equal to",
gte: "Greater than or equal to",
lte: "Less than or equal to",
gt: "Greater than",
lt: "Less than"
}
}
},
reorderable: true, //not working
selectable: "multiple",
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50, 100]
},
height: 430,
width: 300,
toolbar: [
{
name: "my-create",
text: "Add new record"
},
{
name: "save",
text: "save changes"
},
{
name: "cancel",
text: "cancel changes"
},
{
name: "export",
text: "Export To Excel"
}
],
columns: [
// { field: "ProductID", title: "No", width: "90px" },
{title: "No", template: "#= ++record #", width: 45 },
{ field: "ProductName", title: "Product Name", width: "350px" },
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "150px" },
{ field: "Discontinued", title: "Purchase", width: "110px" },
{ field: "TotalStock", title: "Total Stock", width: "150px", footerTemplate: "Total : #= kendo.toString(sum, 'C') #", format: "{0:c2}" }
//{ command: ["destroy"], title: " ", width: "175px" }
],
export: {
cssClass: "k-grid-export-image",
title: "people",
createUrl: "/Home/ExportToExcel",
downloadUrl: "/Home/GetExcelFile"
},
groupable: {
messages: {
empty: "Drop columns here"
}
}, //not working
columnMenu: {
sortable: true,
filterable: true,
messages: {
columns: "Hide/Show Columns",
filter: "Apply filter",
sortAscending: "Sort (asc)",
sortDescending: "Sort (desc)"
}
},
resizable: true,
dataBinding: function () {
record = (this.dataSource.page() - 1) * this.dataSource.pageSize();
},
sortable: {
mode: "multiple"
},
sort: { field: "ProductID", dir: "asc" },
editable: { mode: "incell", createAt: "bottom" }
});
//custom global variables
newRowAdded = false;
checkedOnce = false;
var grid = $("#batchgrid").data("kendoGrid");
$(".k-grid-my-create", grid.element).on("click", function (e) {
window.newRowAdded = true;
var dataSource = grid.dataSource;
var total = dataSource.data().length;
dataSource.insert(total, {});
dataSource.page(dataSource.totalPages());
grid.editRow(grid.tbody.children().last());
});
grid.bind("saveChanges", function () {
window.newRowAdded = false;
// var grid = $("#batchgrid").data("kendoGrid");
// grid.dataSource.sort({ field: "ProductID", dir: "asc" });
// GetValOf();
// var grid = $('#batchgrid').data("kendoGrid");
// var total = 0;
// $.each(grid.dataSource.view(), function () {
// total += this.TotalStock;
// });
// alert(total);
});
grid.bind("cancelChanges", function () {
window.newRowAdded = false;
});
$(".k-grid-export", "#batchgrid").bind("click", function (ev) {
// your code
// alert("Hello");
var grid = $("#batchgrid").data("kendoGrid");
grid.dataSource.pageSize(parseInt($("#batchgrid").data("kendoGrid").dataSource.data().length));
excelImport();
});
});
</script>
but i got some example code for importing grid data to excel and in there they used asp.net mvc syntax.
here is the code.
#(
Html.Kendo().Grid(Model).Name("Grid")
.DataSource(ds => ds.Ajax()
.Model(m =>
{
m.Id(p=>p.ProductID);
})
.Read(r => r.Action("Read", "Home"))
)
.ToolBar(toolBar =>
toolBar.Custom()
.Text("Export To Excel")
.HtmlAttributes(new { id = "export" })
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
)
.Columns(columns =>
{
columns.Bound(p => p.ProductID);
columns.Bound(p => p.ProductName);
columns.Bound(p => p.UnitPrice).Format("{0:c}");
columns.Bound(p => p.QuantityPerUnit);
})
.Events(ev => ev.DataBound("onDataBound"))
.Pageable()
.Sortable()
.Filterable()
)
but my problem is i need to add below line of code to my grid(in first code mentioned above).
.ToolBar(toolBar =>
toolBar.Custom()
.Text("Export To Excel")
.HtmlAttributes(new { id = "export" })
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
)
but im stucked with this single line
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
can somebody please tell me that how to use this code in my html grid..
Write Toolbar manual
<div class="k-toolbar k-grid-toolbar k-grid-top">
<a class="k-button k-button-icontext " id="exportCsv" href="/Home/ExportToCsv?take=50&skip=0&page=1&pageSize=10&filter=~&sort=" id="exportToCSV"><span></span>Export CSV</a>
<a class="k-button k-button-icontext " id="exportXls" href="/Home/ExportToXls?take=50&skip=0&pageSize=10&filter=~&sort=" id="exportToExcel"><span></span>Export Excel</a>
</div>
then add databound to kendoGrid
....
editable: false, // enable editing
sortable: true,
filterable: true,
scrollable: false,
dataBound: onDataBound,
columns: [.....
then write 'onDataBound' function
<script>
function onDataBound(e) {
var grid = $('#grid').data('kendoGrid');
var take = grid.dataSource.take();
var skip = grid.dataSource.skip();
var page = grid.dataSource.page();
var sort = grid.dataSource.sort();
var pageSize = grid.dataSource.pageSize();
var filter = JSON.stringify(grid.dataSource.filter());
// Get the export link as jQuery object
var $exportLink = $('#exportXls');
// Get its 'href' attribute - the URL where it would navigate to
var href = $exportLink.attr('href');
// Update the 'take' parameter with the grid's current page
href = href.replace(/take=([^&]*)/, 'take=' + take || '~');
// Update the 'skip' parameter with the grid's current page
href = href.replace(/skip=([^&]*)/, 'skip=' + skip || '~');
// Update the 'page' parameter with the grid's current page
href = href.replace(/page=([^&]*)/, 'page=' + page || '~');
// Update the 'sort' parameter with the grid's current sort descriptor
href = href.replace(/sort=([^&]*)/, 'sort=' + sort || '~');
// Update the 'pageSize' parameter with the grid's current pageSize
href = href.replace(/pageSize=([^&]*)/, 'pageSize=' + pageSize);
//update filter descriptor with the filters applied
href = href.replace(/filter=([^&]*)/, 'filter=' + (filter || '~'));
// Update the 'href' attribute
$exportLink.attr('href', href);
$('#exportCsv').attr('href', href.replace('ExportToXls', 'ExportToCsv'));
}
</script>
And this is the Action, and parameters
public FileResult ExportToXls(int take, int skip, IEnumerable<Sort> sort, string filter)
{
try
{
Filter objfilter = JsonConvert.DeserializeObject<Filter>(filter);
var lstContactFormData = XmlData.GetIletisimBilgileri().OrderByDescending(i => i.tarih);
//Get the data representing the current grid state - page, sort and filter
//IEnumerable products = _db.Products.ToDataSourceResult(request).Data;
IEnumerable contactsDatas = lstContactFormData.AsQueryable().ToDataSourceResult(take, skip, sort, objfilter).Data;
...
...
I retrieve images against specific id and display as data view using ExtJS 4. Now I need to call function by dbl clicking the image.
Ext.define('${pkgName}.v02x003001.SV02X00300102', {
extend: 'Ext.view.View',
alias: 'widget.sv02x00300102',
id: 'images-view',
autoScroll: true,
trackOver: true,
multiSelect: true,
height: 180,
overItemCls: 'x-item-over',
itemSelector: 'div.thumb-wrap',
emptyText: 'No images to display',
prepareData: function (data) {
Ext.apply(data, {
shortName: Ext.util.Format.ellipsis(data.name, 15),
sizeString: Ext.util.Format.fileSize(data.size),
dateString: Ext.util.Format.date(data.lastmod, "m/d/Y g:i a")
});
return data;
},
initComponent: function () {
var me = this;
var member = Ext.getCmp('member-sv02x00300104').getValue();
me.store = 'S02X003001';
me.tpl = [
'<tpl for=".">',
'<div class="thumb-wrap" id="{name}">',
'<div class="thumb">
<img src="${createLink(mapping:'
img ', params:[])}/{id}/100/100/" title="{id}">
</div>',
'<span class="x-editable">{name}</span></div>',
'</tpl>',
'<div class="x-clear"></div>'];
me.callParent(arguments);
}
});
Does this code suits your needs (doc here)?
listeners: {
itemdblclick: function (view, record, item, index, e) {
if (Ext.get(e.getTarget()).is('img')) {
alert('you double clicked an image');
}
}
}