///
///
var self = this;
self.Employees = ko.observableArray([]);
self.Message = ko.observable(); // The Observable for displaying Message
//The Logic for Pagination Here
self.pageRowSize = ko.observable(5); // The Default No of Rows on the Table.
self.currentPage = ko.observable(0); // The current Page.
self.paginationEmployee = ko.observableArray(); // The declaration for Paginated data storing .
//The computed declaration for the number of display of records
self.page = ko.computed(function ()
{
// Logic for displaying number of rows in the table
if (self.pageRowSize() == "all")
{
self.paginationEmployee(self.Employees.slice(0));
}
else
{
var pgSize = parseInt(self.pageRowSize(), 10), first = pgSize * self.currentPage(), last = first + pgSize;
self.paginationEmployee(self.Employees.slice(first, last));
}
}, self);
self.totalPages = function () { var totpages = self.Employees().length / self.pageRowSize() || 1; return Math.ceil(totpages); }
self.nextPage = function () { if (self.currentPage() < self.totalPages() - 1) { self.currentPage(self.currentPage() + 1); } }
self.previousPage = function () { if (self.currentPage() > 0) { self.currentPage(self.currentPage() - 1); } }
self.firstPage = function () { self.currentPage(0); }
self.lastPage = function () { self.currentPage(self.totalPages() + 1) }
//S3: The function for sort
self.sortAscDesc = function (h, e) {
if (self.defaultSort === h) { h.ascending = !h.ascending; } //toggle across asc and desc Soring
else { self.defaultSort = h; } //first click store as the default action
var key = self.defaultSort.sortKeyName;
var keyAB = self.defaultSort.rule;
var sortingAsc = function (l, r) { return l[key] < r[key] ? -1 : l[key] > r[key] ? 1 : l[key] == r[key] ? 0 : 0; };
var sortingDesc = function (l, r) { return l[key] > r[key] ? -1 : l[key] < r[key] ? 1 : l[key] == r[key] ? 0 : 0; };
var sortingAscD = function (l, r) {
return moment(l[key]).format('YYYYMMDD') < moment(r[key]).format('YYYYMMDD') ? -1 :
moment(l[key]).format('YYYYMMDD') > moment(r[key]).format('YYYYMMDD') ? 1 :
l[key] == r[key] ? 0 : 0;
};
var sortingDescD = function (l, r) {
return moment(l[key]).format('YYYYMMDD') > moment(r[key]).format('YYYYMMDD') ? -1 :
moment(l[key]).format('YYYYMMDD') < moment(r[key]).format('YYYYMMDD') ? 1 :
l[key] == r[key] ? 0 : 0;
};
var sorting = self.defaultSort.ascending ? keyAB == 'A' ? sortingAsc : sortingAscD : keyAB == 'A' ? sortingDesc : sortingDescD; // The Sorting condition
self.paginationEmployee.sort(sorting); // Apply the effect on the Array
};
// Debug Helper
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.Employees)/*, null, 2*/));
};
self.lastSavedJson = ko.observable("");
//S1: An Observable Array declaration for
self.tableHeadersCaptions = ko.observableArray([
{ caption: 'Id', sortKeyName: 'Id', ascending: true, rule: 'A' },
{ caption: 'KeyName', sortKeyName: 'KeyName', ascending: true, rule: 'A' },
{ caption: 'Flag', sortKeyName: 'Flag', ascending: true, rule: 'A' },
{ caption: 'Amount', sortKeyName: 'Amount', ascending: true, rule: 'A' },
{ caption: 'Number', sortKeyName: 'Number', ascending: true, rule: 'A' },
{ caption: 'Birthday', sortKeyName: 'Birthday', ascending: true, rule: 'D' } /* sort the date using moment ansi string ccyymmdd */
]);
// DEVELOPER: Could create a dictionary of these for each table in the database.
//S2: The Default Sort
self.defaultSort = self.tableHeadersCaptions[0];
// Ends Here
// Logic for CRUD Operations
//S2:Method to Load all Employees by making Ajax call to WEB API GET method
function loadEmployees() {
var url = top.location.host; if (url == "localhost") url += "/montegodata"; url = "http://" + url + "/Holding/GridPage";
//alert("In Load "+url );
$.ajax({
type: "GET",
url: url,
success: function (data) {
//self.Message("Success");
self.Employees(data);
},
error: function (err) {
alert(err.status + " <--------------->");
}
});
};
//S3:The Employee Object
function Employee(txtId, txtkeyname, txtflag, txtamount, txtnumber, txtbirthday)
{
return { Id: ko.observable(txtId), KeyName: ko.observable(txtkeyname), Flag: ko.observable(txtflag),
Amount: ko.observable(txtamount), Number: ko.observable(txtnumber), Birthday: ko.observable(txtbirthday) }
};
//S4:The ViewModel where the Templates are initialized
var OperationsViewModel = {
displayOnlyTemplate: ko.observable("displayOnlyTemplate"),
updateTemplate: ko.observable()
};
//S5:Method to decide which Template is used (displayOnlyTemplate or updateTemplate)
OperationsViewModel.currentTemplate = function (tmpl) {
return tmpl === this.updateTemplate() ? 'updateTemplate' : this.displayOnlyTemplate();
}.bind(OperationsViewModel);
//S9:Method to Reset the template
OperationsViewModel.reset = function (t) {
this.updateTemplate("displayOnlyTemplate");
};
//S8:Method to Delete the Record
OperationsViewModel.deleteEmployee = function (d) {
var url = top.location.host; if (url == "localhost") url += "/montegodata"; url = "http://" + url + "/Holding/DeleteEasy/";
$.ajax({
type: "DELETE",
url: url + d.Id,
success: function (changedRecord) {
var record = ko.utils.arrayFirst(self.Employees(), function (item) { return item.Id === changedRecord.holding.Id; });
self.Employees.remove(record);
OperationsViewModel.reset();
self.Message("Record Deleted Successfully ");
},
statusCode: {
404: function () { self.Message("Could not contact server. ? [ValidateAntiForgeryToken]"); },
500: function () { self.Message("[" + url + "] A server-side error has occurred."); }
},
error: function (err) {
self.Message("The Ajax Delete Called Failed With: " + err.status);
OperationsViewModel.reset();
}
});
};
//S6:Method to create a new Blank entry When the Add New Record button is clicked
OperationsViewModel.addnewRecord = function () {
var now = new Date();
self.paginationEmployee.push(new Employee(0, "", "", 0.0, 0, now.toString("DD-MMM-YYYY")));
};
//S7:Method to Save the Record (This is used for Edit and Add New Record)
OperationsViewModel.saveEmployee = function (d)
{
var url = top.location.host; if (url == "localhost") url += "/montegodata"; url = "http://" + url + "/Holding/Update";
var birthdate1 = moment(d.Birthday).format('DD-MMM-YYYY');
var birthdate2 = $("#txtbirthday").val();
var Emp = {};
Emp.Id = d.Id;
Emp.KeyName = d.KeyName;
Emp.Flag = d.Flag;
Emp.Amount = d.Amount;
Emp.Number = d.Number;
Emp.Birthday = $("#txtbirthday").val(); // moment(d.Birthday).format('DD-MMM-YYYY');
//Get var bla = $('#txt_name').val();
//Set $('#txt_name').val('bla');
//Edit the Record
$.ajax({
type: "POST",
url: url,
data: Emp,
success: function (changedRecord) {
var record = ko.utils.arrayFirst(self.Employees(), function (item) { return item.Id === changedRecord.record.Id; });
if (record != null) {
record.KeyName = changedRecord.record.KeyName;
record.Flag = changedRecord.record.Flag;
record.Amount = changedRecord.record.Amount;
record.Number = changedRecord.record.Number;
record.Birthday = changedRecord.record.Birthday;
}
else
{
record = ko.utils.arrayFirst(self.Employees(), function (item) { return item.Id == 0; });
if (record != null) {
record.Id = changedRecord.record.Id;
record.KeyName = changedRecord.record.KeyName;
record.Flag = changedRecord.record.Flag;
record.Amount = changedRecord.record.Amount;
record.Number = changedRecord.record.Number;
record.Birthday = changedRecord.record.Birthday;
} else { self.Employees().push(changedRecord.record); }
}
self.Message("Record Updated Successfully");
OperationsViewModel.reset();
},
error: function (err) {
self.Message("Error Occures, Please Reload The Page And Try Again " + err.status);
OperationsViewModel.reset();
}
});
};
loadEmployees();
ko.applyBindings(OperationsViewModel);
ko.bindingHandlers.date = {
init: function (element, valueAccessor) {
try {
var jsonDate = ko.utils.unwrapObservable(valueAccessor());
if ($(element).is("input") === true)
{
$(element).val(moment(jsonDate).format('DD-MMM-YYYY'));
}
else
{
$(element).text(moment(jsonDate).format('DD-MMM-YYYY'));
}
}
catch (exc) { } //attach an event handler to our dom element to handle user input
element.onchange = function () {
var value = valueAccessor(); //get our observable
//set our observable to the parsed date from the input
if ($(element).is("input") === true) {
$(element).text(moment(value).format('DD-MMM-YYYY'));
}
else {
$(element).val(moment(value).format('DD-MMM-YYYY'));
}
value = moment(element.value, 'DD-MMM-YYYY').toDate();
};
/*
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
observable( $(element).datepicker("getDate") );
});
*/
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
if (valueUnwrapped) {
//if ($(element).is("input") === true)
// element.value= moment(valueUnwrapped).format('DD-MMM-YYYY') ;
//else
// element.innerText=moment(valueUnwrapped).format('DD-MMM-YYYY');
element.value = moment(valueUnwrapped).format('DD-MMM-YYYY');
}
}
};
//Ends Here