How to Pass Value from Control to View Json - asp.net-mvc

I am a beginner in ASP.NET MVC. Here is my code, I'm looking for expert help.
In this code i am calculating SaleTotal
[HttpPost]
public double SaleTotal(DateTime? FromDate, DateTime? ToDate)
{
var Sales = from s in db.SalesMasters
where (s.BillDate >= FromDate && s.BillDate <= ToDate)
select s.STotal;
var SalesReturn = from s in db.SReturnMasters
where s.ReturnDate >= FromDate && s.ReturnDate <= ToDate
select s.SRTotal;
double TotalSales = Sales.Sum().GetValueOrDefault();
double TotalSalesReturn = SalesReturn.Sum().GetValueOrDefault();
double Balance = TotalSales - TotalSalesReturn;
return Balance;
}
public ActionResult AllSaleReport(JQueryDataTableParamModel param, int? BillNo , DateTime ? FromDate,DateTime? ToDate)
{
double SalesTotal=SaleTotal(FromDate, ToDate);
var Sales = (from S in db.SalesMasters
where (S.BillDate >= FromDate && S.BillDate <= ToDate )
select S).ToList();
var filteredSales=(from S in db.SalesMasters
where (S.BillDate >= FromDate && S.BillDate <= ToDate && S.CancelFlag==false )
select S).ToList();
var result = from S in filteredSales.Skip(param.iDisplayStart).Take(param.iDisplayLength)
select new[] { S.BillDate.GetValueOrDefault().ToString("dd-MMM-yyyy"), Convert.ToString(S.BillNo), S.RefName, S.Paymode, Convert.ToString(S.NetAmt) };
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = Sales.Count,
iTotalDisplayRecords = filteredSales.Count,
aaData = result,
SalesReturn = SaleTotal(FromDate, ToDate)
},
JsonRequestBehavior.AllowGet);
}
My JavaScript to load data to DataTable
function LoadAllData() {
var reportTable = $('#AllSales').dataTable({
"processing": true,
//"bprocessing": true,
"bJQueryUI": false,
"bServerSide": true,
"bFilter": false,
//"bAutoWidth": true,
"bDestroy": true,
"iDisplayLength": 20,
//"sProcessing": "<img src=~/Content/images/ajax-loader.gif />",
"dom": 'T<"clear">lfrtip',
"sSwfPath": "~/swf/copy_csv_xls_pdf.swf",
"fnPreDrawCallback": function () {
$("#AllSales").hide();
$("#loading").show();
// alert("Pre Draw");
},
"fnDrawCallback": function () {
$("#AllSales").show();
$("#loading").hide();
// alert("Draw");
},
"fnInitComplete": function () {
},
"fnServerParams": function (aoData) {
aoData.push({ "name": "FromDate", "value": $("#FromDate").val() })
aoData.push({ "name": "ToDate", "value": $("#ToDate").val() })
},
"sAjaxSource": "/Report/AllSaleReport",
"footerCallback": function (row, aoData, start, end, display) {
var api = this.api(), aoData;
// Remove the formatting to get integer data for summation
var intVal = function (i) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '') * 1 :
typeof i === 'number' ?
i : 0;
};
// Total over all pages
data = api.column(4).data();
alert(data.length);
// alert(SalesReturn);
total = data.length ?
data.reduce(function (a, b) {
return intVal(a) + intVal(b);
}) :
0;
// Total over this page
data = api.column(4, { page: 'current' }).data();
pageTotal = data.length ?
data.reduce(function (a, b) {
return intVal(a) + intVal(b);
}) :
0;
// Update footer
$(api.column(4).footer()).html(
'$' + pageTotal + ' ( $' + total + ' total)'
);
}
});
};
I want to pass SaleTotal to DataTable or my View
How can I Pass SaleTotal from controller to view. I tried many ways but still my problem not solved.

If I understand this correctly the data you want is the data from the SaleTotal method.
That data is in the json returned from the AllSaleReport method:
return Json(new
{
...
SalesReturn = SaleTotal(FromDate, ToDate)
},
So when you call the AllSaleReport from DataTable use fnServerData to override the function that gets that data and insert it where you want it. Something like:
"fnServerData": function (sSource, aoData, fnCallback) {
$.getJSON(sSource, aoData, function (result) {
var saleTotal = result.SalesReturn;
// Insert saleTotal in footer
fnCallback(result);
});
},

Related

select2 + large number of records

I am using select2 dropdown. It's working fine for smaller number of items.
But when the list is huge (more than 40000 items) it really slows down. It's slowest in IE.
Otherwise simple Dropdownlist works very fast, till 1000 records. Are there any workarounds for this situation?
///////////////**** Jquery Code *******///////////////
var CompanypageSize = 10;
function initCompanies() {
var defaultTxtOnInit = 'a';
$("#DefaultCompanyId").select2({
allowClear: true,
ajax: {
url: "/SignUpTemplate/GetCompanies",
dataType: 'json',
delay: 250,
global: false,
data: function (params) {
params.page = params.page || 1;
return {
keyword: params.term ? params.term : defaultTxtOnInit,
pageSize: CompanypageSize,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.result,
pagination: {
more: (params.page * CompanypageSize) < data.Counts
}
};
},
cache: true
},
placeholder: {
id: '0', // the value of the option
text: '--Select Company--'
},
width: '100%',
//minimumInputLength: 3,
});
}
//////////******* Have to initialise in .ready *******///////////////
$(document).ready(function () {
initCompanies();
});
//////////******* C# code :: Controller is : SignUpTemplateController************/////
public JsonResult GetCompanies(string keyword, int? pageSize, int? page)
{
int totalCount = 0;
if (!string.IsNullOrWhiteSpace(keyword))
{
List<Companies> listCompanies = Companies.GetAll(this.CurrentTenant, (keyword ?? string.Empty).Trim(), false, 11, page.Value, pageSize.Value, ref totalCount, null, null, null, null, null).ToList();
var list = listCompanies.Select(x => new { text = x.CompanyName, id = x.CompanyId }).ToList();
return Json(new { result = list, Counts = totalCount }, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}

Select2 doesn't work change value from jQuery (dataAdapter)

I have a huge json data source (over 50,000 + lines) loaded in memory from a static file.
Note: It's not important why I have it in a static file.
I use select2 (v 4.0.5) that initializes as:
function initSelect2(selectName, dataSelect) {
var pageSize = 20;
$.fn.select2.amd.require(["select2/data/array", "select2/utils"],
function (ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
if (!("page" in params)) {
params.page = 1;
}
var data = {};
data.results = dataSelect.slice((params.page - 1) * pageSize, params.page * pageSize);
data.pagination = {};
data.pagination.more = params.page * pageSize < dataSelect.length;
callback(data);
};
$('#mySelect3').select2({
ajax: {},
dataAdapter: CustomData,
width: '100%'
});
});
}
I have one big problem. I can not set the value to select from jQuery. If I try like this:
$ ("#mySelect3").val(17003).trigger("change");
nothing will happen. But I think I'm doing it badly. If I understand the documentation I think I should implement function:
CustomData.prototype.current = function (callback) {}
that should create the data, and then function:
CustomData.prototype.query = function (params, callback) {}
should only filter them.
Can you please help me, how do I implement select2 initialization, that can work with many options and can by set from jQuery?
With custom data adapter you don't need pagination :
// create huge array
function mockData() {
var hugeArray = [];
for (let i = 0; i < 50000; i++) {
el = {
id: i,
text: 'My mock data ' + i,
};
hugeArray.push(el);
}
return hugeArray;
};
// define custom dataAdapter
$.fn.select2.amd.define("myCustomDataAdapter",
['select2/data/array','select2/utils'],
function (ArrayData, Utils) {
function CustomData ($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
// here replace mockData() by your array
results: mockData()
};
callback(data);
};
return CustomData;
}
);
//
$('#mySelect3').select2({
allowClear: true,
// use dataAdapter here
dataAdapter:$.fn.select2.amd.require("myCustomDataAdapter"),
});
And with search you can do like this :
// create huge array
function mockData() {
var hugeArray = [];
for (let i = 0; i < 50000; i++) {
el = {
id: i,
text: 'My mock data ' + i,
};
hugeArray.push(el);
}
return hugeArray;
};
// define custom dataAdapter
$.fn.select2.amd.define("myCustomDataAdapter",
['select2/data/array','select2/utils'],
function (ArrayData, Utils) {
function CustomData ($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
// here replace mockData() by your array
results: mockData()
};
if ($.trim(params.term) === '') {
callback(data);
} else {
if (typeof data.results === 'undefined') {
return null;
}
var filteredResults = [];
data.results.forEach(function (el) {
if (el.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
filteredResults.push(el);
}
});
if (filteredResults.length) {
var modifiedData = $.extend({}, data, true);
modifiedData.results = filteredResults;
callback(modifiedData);
}
return null;
}
};
return CustomData;
}
);
//
$('#mySelect3').select2({
minimumInputLength: 2,
tags: false,
allowClear: true,
// use dataAdapter here
dataAdapter:$.fn.select2.amd.require("myCustomDataAdapter"),
});
I had the same issue and this is how I solved it.
Note: We are using dataAdapter because we dealing with large that, so I am assuming your drop-down will contain large amount of data.
After implementing your DataAdapter with a query use this example to initialize your select2.
if(selectedValue !== null )
{
$("#item_value").select2({
placeholder: 'Select an option',
allowClear: true,
disabled: false,
formatLoadMore: 'Loading more...',
ajax: {},
data: [{ id: selectedValue, text: selectedValue }],
dataAdapter: customData
});
$("#item_value").val(selectedValue).trigger('change');
}else{
$("#item_value").select2({
placeholder: 'Select an option',
allowClear: true,
disabled: false,
formatLoadMore: 'Loading more...',
ajax: {},
dataAdapter: customData
});
}
To set selected value in select2 you need to pass some data into data option, but as we are dealing with large amount of data. You can't pass the complete array of large data you have as it's going to cause your browser window to freeze and lead to a bad user performance.
But instead set the data option only with the selected value you got from db or variable.
I hope this helps.

Open prepopulated SQLite data base in react-native, where to put database?

I am following instructions on importing existing db to my App
(for IOS):https://www.npmjs.com/package/react-native-sqlite
Have created www folder in myProject directory, put there myDataBase.
Added folder to xcode.
this is my src code to open it and make a query :
import SQLite from 'react-native-sqlite-storage'
function errorCB(err) {
console.log("SQL Error: " + err);
}
function successCB() {
console.log("SQL executed fine");
}
function openCB() {
console.log("Database OPENED");
}
console.log('database.js')
var db = null;
export function openDB() {
// var db = SQLite.openDatabase("test.db", "1.0", "Test Database", 200000, openCB, errorCB);
db = SQLite.openDatabase({name : "words", createFromLocation : 1}, openCB,errorCB);
}
export function getWord(str) {
db.transaction((tx) => {
tx.executeSql("SELECT * FROM words", [], (tx, results) => {
console.log("Query completed");
// Get rows with Web SQL Database spec compliance.
var len = results.rows.length;
console.log('len' + len)
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
console.log(`word: ${row.str}, Dept Name: ${row.smth}`);
}
// Alternatively, you can use the non-standard raw method.
/*
let rows = results.rows.raw(); // shallow copy of rows Array
rows.map(row => console.log(`Employee name: ${row.name}, Dept Name: ${row.deptName}`));
*/
});
});
}
I am getting:
Built path to pre-populated DB asset from app bundle www subdirectory: /Users/mac/Library/Developer/CoreSimulator/Devices/06420F74-0E1C-47C1-BCAC-5D3574577349/data/Containers/Bundle/Application/75EE8E9A-276F-402F-982A-DBF30DE80802/MyApp.app/www/words
RCTLog.js:48 target database location: nosync
RCTLog.js:48 Opening db in mode READ_WRITE, full path: /Users/mac/Library/Developer/CoreSimulator/Devices/06420F74-0E1C-47C1-BCAC-5D3574577349/data/Containers/Data/Application/67D2451F-3D72-4B82-AC90-AD6DB9A82566/Library/LocalDatabase/words
Database opened
RCTLog.js:48 Good news: SQLite is thread safe!
dataBase.js:13 Database OPENED
RCTLog.js:48 open cb finished ok
sqlite.core.js:475 Error handler not provided: {message: "no such table: words", code: 5}
sqlite.core.js:572 warning - exception while invoking a callback: {"code":5}
Don't know what is the reason of this error?
I have checked in DB browser for SQLite that DB is correct and table 'words' exists in it and have rows in it.
I have tried different names for db file: 'words', 'words.db', 'words.sqlite' nothing helps.
I am running my app from console as :
react-native run-ios
SQLite.openDatabase({name:"testDB.sqlite3", createFromLocation:1,location:'Library'})
This solved my problem. testDB.sqlite3 file size is 24 MB.
testDB.sqlite and testDB.db not working, but testDB.sqlite3 is working.
Here I build a Repository, hop it help you
import BaseModule from '../baseModule';
import * as SQLite from 'expo-sqlite';
import * as MediaLibrary from 'expo-media-library';
import * as FileSystem from 'expo-file-system';
import * as Permissions from 'expo-permissions';
import DetaliItemsSettings from '../detaliItemSettings';
import ChapterSettings from '../chapterSettings';
import httpClient from '../http';
export type NovelReaderSettingsType = (items: BaseModule) => void;
export type Find = (foundItems: BaseModule[]) => void;
export default class Repository {
static dbIni: Boolean;
databaseName: string;
constructor() {
this.databaseName = 'test.db';
}
importSettings = async (uri: string) => {
try {
const {status} = await Permissions.askAsync(Permissions.MEDIA_LIBRARY);
if (status === 'granted') {
var json = await FileSystem.readAsStringAsync(uri, {encoding: 'utf8'});
if (json) console.log(json);
var item = JSON.parse(json) as {
applicationSettings: any;
items: DetaliItemsSettings[];
};
var appSettings = await this.where('ApplicationSettings');
if (item.applicationSettings) {
item.applicationSettings = httpClient.cloneItem(
appSettings.length > 0 ? appSettings[0] : {},
item.applicationSettings,
['id', 'tableName'],
);
await this.save(
item.applicationSettings,
undefined,
'ApplicationSettings',
);
}
if (item.items && item.items.length > 0) {
for (var i = 0; i < item.items.length; i++) {
var a = item.items[i];
var b = (await this.where('DetaliItems', {
novel: a.novel,
})) as DetaliItemsSettings[];
var aChapterSettings =
a.chapterSettings ?? ([] as ChapterSettings[]);
var bChaptersSettings =
b && b.length > 0
? ((await this.where('Chapters', {
detaliItem_Id: b[0].id,
})) as ChapterSettings[])
: ([] as ChapterSettings[]);
var updatedChapterSettings = [] as ChapterSettings[];
if (b && b.length > 0) {
if (a.chapterIndex) b[0].chapterIndex = a.chapterIndex;
b[0].isFavorit = true;
a = b[0];
}
aChapterSettings.forEach((x) => {
var bCh = bChaptersSettings.find(
(a) => a.chapterUrl === x.chapterUrl,
);
if (bCh)
updatedChapterSettings.push(
httpClient.cloneItem(bCh, x, ['id', 'tableName']),
);
else updatedChapterSettings.push(x);
});
let detaliItemSettings = await this.save(
a,
undefined,
'DetaliItems',
);
for (var y = 0; y <= aChapterSettings.length - 1; y++) {
let m = aChapterSettings[y];
m.detaliItem_Id = detaliItemSettings.id;
await this.save(m, undefined, 'Chapters');
}
}
}
return true;
}
} catch (error) {
console.log(error);
}
return false;
};
exportFileToDownloadFolder = async () => {
try {
const {status} = await Permissions.askAsync(Permissions.MEDIA_LIBRARY);
if (status === 'granted') {
var favoriteData = (await this.where('DetaliItems', {
isFavorit: true,
})) as DetaliItemsSettings[];
for (var i = 0; i < favoriteData.length; i++) {
var item = favoriteData[i];
item.chapterSettings = (await this.where('Chapters', {
detaliItem_Id: item.id,
})) as ChapterSettings[];
item.id = 0;
item.chapterSettings.forEach((x) => {
x.id = 0;
x.detaliItem_Id = 0;
});
}
var result = {
applicationSettings:
(await this.where('ApplicationSettings')).length > 0
? (await this.where('ApplicationSettings'))[0]
: undefined,
items: favoriteData,
};
let fileUri = FileSystem.documentDirectory + 'NovelManager.db';
await FileSystem.writeAsStringAsync(fileUri, JSON.stringify(result), {
encoding: FileSystem.EncodingType.UTF8,
});
const asset = await MediaLibrary.createAssetAsync(fileUri);
await MediaLibrary.createAlbumAsync('Download', asset, false);
return true;
}
} catch (error) {
console.log(error);
}
return false;
};
dataBasePath = () => {
return FileSystem.documentDirectory + this.databaseName;
};
createConnection = () => {
return SQLite.openDatabase(this.databaseName);
};
allowedKeys = (tableName: string) => {
return new Promise((resolve, reject) => {
this.createConnection().transaction(
(x) =>
x.executeSql(
`PRAGMA table_info(${tableName})`,
undefined,
(trans, data) => {
var keys = [] as string[];
for (var i = 0; i < data.rows.length; i++) {
if (data.rows.item(i).name != 'id')
keys.push(data.rows.item(i).name);
}
resolve(keys);
},
),
(error) => {
reject(error);
},
);
}) as Promise<string[]>;
};
selectLastRecord = async (item: BaseModule) => {
console.log('Executing SelectLastRecord...');
return (
await this.find(
item.id <= 0
? `SELECT * FROM ${item.tableName} ORDER BY id DESC LIMIT 1;`
: `SELECT * FROM ${item.tableName} WHERE id=?;`,
item.id > 0 ? [item.id] : undefined,
)
).map((x) => {
x.tableName = item.tableName;
return x;
});
};
delete = async (item: BaseModule, tableName?: string) => {
tableName = item.tableName ?? tableName;
var q = `DELETE FROM ${tableName} WHERE id=?`;
await this.execute(q, [item.id]);
};
public save = (
item: BaseModule,
insertOnly?: Boolean,
tableName?: string,
) => {
if (!item.tableName) item.tableName = tableName ?? '';
return new Promise(async (resolve, reject) => {
try {
await this.setUpDataBase();
console.log('Executing Save...');
var items = await this.where(item.tableName, {id: item.id});
var keys = (await this.allowedKeys(item.tableName)).filter((x) =>
Object.keys(item).includes(x),
);
let query = '';
let args = [] as any[];
if (items.length > 0) {
if (insertOnly) return;
query = `UPDATE ${item.tableName} SET `;
keys.forEach((k, i) => {
query += ` ${k}=? ` + (i < keys.length - 1 ? ',' : '');
});
query += ' WHERE id=?';
} else {
query = `INSERT INTO ${item.tableName} (`;
keys.forEach((k, i) => {
query += k + (i < keys.length - 1 ? ',' : '');
});
query += ') values(';
keys.forEach((k, i) => {
query += '?' + (i < keys.length - 1 ? ',' : '');
});
query += ')';
}
keys.forEach((k: string, i) => {
args.push(item[k] ?? null);
});
if (items.length > 0) args.push(item.id);
await this.execute(query, args);
resolve((await this.selectLastRecord(item))[0]);
} catch (error) {
console.log(error);
reject(error);
}
}) as Promise<BaseModule>;
};
public find = (query: string, args?: any[]) => {
return new Promise((resolve, reject) => {
this.createConnection().transaction(
async (x) => {
await this.setUpDataBase();
console.log('Executing Find..');
x.executeSql(
query,
args,
async (trans, data) => {
console.log('query executed:' + query);
var items = [] as BaseModule[];
for (var i = 0; i < data.rows.length; i++) {
var t = data.rows.item(i);
items.push(t);
}
resolve(items);
},
(_ts, error) => {
console.log('Could not execute query:' + query);
console.log(error);
reject(error);
return false;
},
);
},
(error) => {
console.log(error);
reject(error);
},
);
}) as Promise<BaseModule[]>;
};
where = async (tableName: string, query?: any) => {
var q = `SELECT * FROM ${tableName} ${query ? 'WHERE ' : ''}`;
var values = [] as any[];
if (query) {
Object.keys(query).forEach((x, i) => {
q += x + '=? ' + (i < Object.keys(query).length - 1 ? 'AND ' : '');
values.push(query[x]);
});
}
return (await this.find(q, values)).map((x) => {
x.tableName = tableName;
return x;
});
};
findOne = async (tableName: string, query?: any) => {
var items = await this.where(tableName, query);
return items && items.length > 0 ? items[0] : undefined;
};
execute = async (query: string, args?: any[]) => {
return new Promise((resolve, reject) => {
this.createConnection().transaction(
(tx) => {
console.log('Execute Query:' + query);
tx.executeSql(
query,
args,
(tx, results) => {
console.log('Statment has been executed....' + query);
resolve(true);
},
(_ts, error) => {
console.log('Could not execute query');
console.log(args);
console.log(error);
reject(error);
return false;
},
);
},
(error) => {
console.log('db executing statement, has been termineted');
console.log(args);
console.log(error);
reject(error);
throw 'db executing statement, has been termineted';
},
);
});
};
public dropTables = async () => {
await this.execute(`DROP TABLE if exists ApplicationSettings`);
await this.execute(`DROP TABLE if exists DetaliItems`);
await this.execute(`DROP TABLE if exists Chapters`);
Repository.dbIni = false;
await this.setUpDataBase();
};
setUpDataBase = async () => {
let applicationSetupQuery = `CREATE TABLE if not exists ApplicationSettings (
id INTEGER NOT NULL UNIQUE,
backGroundColor TEXT NOT NULL,
fontSize INTEGER NOT NULL,
lineHeight INTEGER NOT NULL,
fontFamily TEXT NOT NULL,
marginLeft INTEGER NOT NULL,
marginRight INTEGER NOT NULL,
detaliItem_Id INTEGER,
selectedParserIndex INTEGER,
PRIMARY KEY(id AUTOINCREMENT)
);`;
let detaliItemsQuery = `CREATE TABLE if not exists DetaliItems (
image TEXT NOT NULL,
title TEXT NOT NULL,
description TEXT NOT NULL,
novel TEXT NOT NULL,
parserName TEXT NOT NULL,
chapterIndex INTEGER NOT NULL,
id INTEGER NOT NULL,
isFavorit INTEGER NOT NULL,
PRIMARY KEY(id AUTOINCREMENT)
);`;
let chapterQuery = `CREATE TABLE if not exists Chapters (
id INTEGER NOT NULL UNIQUE,
chapterUrl TEXT NOT NULL,
isViewed INTEGER NOT NULL,
currentProgress NUMERIC NOT NULL,
finished INTEGER NOT NULL,
detaliItem_Id INTEGER NOT NULL,
PRIMARY KEY(id AUTOINCREMENT),
CONSTRAINT "fk_detaliItem_id" FOREIGN KEY(detaliItem_Id) REFERENCES DetaliItems(id)
);`;
if (!Repository.dbIni) {
console.log('dbIni= false, setUpDataBase');
await this.execute(applicationSetupQuery);
await this.execute(detaliItemsQuery);
await this.execute(chapterQuery);
Repository.dbIni = true;
} else {
console.log('dbIni= true, setUpDataBase');
}
};
}

OncellChange Event of Slickgrid

I have a slickgrid with a checkbox column.
I want to capture the row id when the checkbox in the selected row is checked or unchecked.
Attached is the script for slickgrid in my view
I want when user checks the checkbox, active column in database should be set to true and when it is unchecked, Active column should be set to false.
<script type="text/javascript">
//$('input[type="button"]').enabled(false);
var grid;
var columnFilters = {};
var jsonmodel = #Html.Raw(Json.Encode(Model));
//function LoadNewMessagesData(messages) {
var dataView;
var data = [];
////console.log('lena:' + subdata.length);
$.each(jsonmodel, function (idx, spotlight) {
var pd = moment(spotlight.PostedDate);
data.push({ id: spotlight.ID, Department: spotlight.SubSection,Title: spotlight.Title, PostedDate: pd.format('YYYY-MM-DD'), Active: spotlight.Active })
});
var columns = [
{ id: '0', name: "Department", field: "Department", sortable: true},
{ id: '1', name: "Title", field: "Title", sortable: true},
{ id: '2', name: "PostedDate", field: "PostedDate", sortable: true }
];
var checkboxSelector = new Slick.CheckboxSelectColumn({
cssClass: "slick-cell-checkboxsel"
})
columns.push(checkboxSelector.getColumnDefinition());
var options = {
enableCellNavigation: true,
explicitInitialization: true,
enableColumnReorder: false,
multiColumnSort: true,
autoHeight: true,
forceFitColumns: true
};
dataView = new Slick.Data.DataView();
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.setSelectionModel(new Slick.RowSelectionModel());
var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
grid.registerPlugin(checkboxSelector);
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
console.log('testing');
grid.render();
});
dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
var options = grid.getOptions();
if (options.enableAddRow != enableAddRow) {
grid.setOptions({ enableAddRow: enableAddRow });
}
});
var rowIndex;
grid.onCellChange.subscribe(function (e, args) {
console.log('onCellChange');
rowIndex = args.row;
});
if (grid.getActiveCell()) {
}
//onSelectedRowsChanged event, if row number was changed call some function.
grid.onSelectedRowsChanged.subscribe(function (e, args) {
if (grid.getSelectedRows([0])[0] !== rowIndex) {
console.log('onSelectedRowsChanged');
}
});
grid.onSort.subscribe(function (e, args) {
var cols = args.sortCols;
var comparer = function (dataRow1, dataRow2) {
for (var i = 0, l = cols.length; i < l; i++) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
return 0;
}
dataView.sort(comparer, args.sortAsc);
});
grid.init();
dataView.beginUpdate();
dataView.setItems(data);
// dataView.setFilter(filter);
dataView.endUpdate();
//}
function RefreshMessagesGrid() {
//console.log('RefreshMessagesGrid');
//grid.invalidate();
grid.invalidateRows();
// Call render to render them again
grid.render();
grid.resizeCanvas();
}
</script>`enter code here`
Thanks in Advance !!!
You have to bind click event on rows....and get the id of the row whose checkbox is checked/unchecked
function bindClickOnRow() {
if($(this).find('.checkboxClass').attr('checked') == 'checked'){
checked = true;
} else {
checked = false;
}
rowId = $(this).attr('id');
}

Jquery autocomplete Select not working

i want to select the Autocomplete box item list . but it is not working . i have write this code to get the item. whenever i use self._renderItemData = function (ul, item) this function customized way the selection stops and when i comment this function my code works fine . please help me to know where am i wrong. i have used jquery ui 1.9 to write the code.
$(document).ready(function () {
var term = "";
var type = "";
var key = "";
$("#searchTextBox").autocomplete({
minLength: 2,
autoFocus: true,
source: function (request, response) {
$.ajax({
url: "../CustomHandlers/SearchHandler.ashx",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: { term: request.term },
success: function (data) {
if (!data || data.length == 0) {
response([{
label: "noMatched",
hcount:0,
type: "noResult",
key: "noResult"
}]);
}
else {
response($.map(data, function(item) {
return {
label: item.label,
hcount:item.record,
type: item.type,
key: item.key
}
}))
}
}
});
$.ui.autocomplete.prototype._renderMenu=function (ul, items) {
var self = this;
currentType = "";
$.each(items, function (index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>" + item.type + "</li>");
currentType = item.type;
}
self._renderItemData(ul, item);
});
self._renderItemData = function (ul, item) {
var searchhtml = "<a class='autocomplitList'>" + item.label + "<span>" + "(" + item.hcount + ") " + "</span>" + "</a>";
return $("<li></li>")
.data("item.autocomplete", item)
.append(searchhtml)
.appendTo(ul);
};
}
}
, select: function (event, ui)
{
term = ui.item.label;
type = ui.item.type;
key = ui.item.key;
// ui.item.option.selected = true;
// $("#searchTextBox").val(ui.item.label);
// return false;
//var selectedObj = ui.item.key;
// alert("Selected: " + selectedObj);
}
,open: function (event, ui) {
//event.addClass("nodis");
}
,close: function () {
// event.removeClass("nodis")
this._trigger("close");
}
});
Try this
$(document).ready(function() {
var term = "";
var type = "";
var key = "";
$.ui.autocomplete.prototype._renderMenu = function(ul, items) {
var self = this;
currentType = "";
$.each(items, function(index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>"
+ item.type + "</li>");
currentType = item.type;
}
self._renderItemData(ul, item);
});
self._renderItemData = function(ul, item) {
var searchhtml = "<a class='autocomplitList'>" + item.label
+ "<span>" + "(" + item.hcount + ") " + "</span>" + "</a>";
return $("<li></li>").data("item.autocomplete", item)
.append(searchhtml).appendTo(ul);
};
}
$("#searchTextBox").autocomplete({
minLength : 2,
autoFocus : true,
source : function(request, response) {
response([{
label : "Value 1",
hcount : 0,
type : "t1",
key : "v1"
}, {
label : "Value 2",
hcount : 0,
type : "t1",
key : "v2"
}, {
label : "Value 3",
hcount : 0,
type : "t2",
key : "v3"
}, {
label : "Value 4",
hcount : 0,
type : "t3",
key : "v4"
}]);
}
,
select : function(event, ui) {
term = ui.item.label;
type = ui.item.type;
key = ui.item.key;
// ui.item.option.selected = true;
// $("#searchTextBox").val(ui.item.label);
// return false;
// var selectedObj = ui.item.key;
// alert("Selected: " + selectedObj);
},
open : function(event, ui) {
// event.addClass("nodis");
},
close : function() {
// event.removeClass("nodis")
this._trigger("close");
}
});
$("#searchTextBox").data('autocomplete')._renderMenu = function(ul, items) {
var that = this;
var currentType = "";
$.each(items, function(index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>"
+ item.type + "</li>");
currentType = item.type;
}
$("<li></li>").addClass('newp').append($("<a></a>")
.text(item.label)).appendTo(ul).data(
"ui-autocomplete-item", item);;
});
}
});
Demo: Fiddle

Resources