Reload DataTable on Every Page Refresh - javascript

All I am trying to do is that I want to refresh my DataTable when the page is relaoded/refreshed. Right now on refreshing the page it retains its data. My application is using ASP.Net MVC tech.
Here is my Data Table and relevant functions:
$(document).ready(function () {
//debugger;
var table = $('#user_session_center_grid').DataTable({
"searching": false,
"colReorder": true,
"lengthChange": false,
"processing": true,
"serverSide": true,
"autoWidth": false,
"ajax": {
cache: false,
url: "#Url.Action("GetUserSessionHistory", "LoggedIn")",
type: 'POST',
data: function (data) {
data.SortBy = 'Month';
data.FromDate = "";
data.ToDate = "";
data.userSearch = $('#userSearch').val();
if (event) {
var objDtFilter = event.target;
if ($(objDtFilter).hasClass('dtFilter')) {
data.FromDate = event.target.getAttribute('fromdt');
data.ToDate = event.target.getAttribute('todt');
}
if ($(objDtFilter).hasClass('dtSort'))
data.SortBy = event.target.getAttribute('sort');
if ($(objDtFilter).hasClass('UserTypeFilter'))
data.value1 = event.target.getAttribute('value');
console.log(data.value1);
}
},
},
"language": {
oPaginate: {
sNext: '<i class="fa fa-chevron-right"></i>',
sPrevious: '<i class="fa fa-chevron-left"></i>',
sFirst: '<i class="fa fa-chevron-right"></i>',
sLast: '<i class="fa fa fa-chevron-left"></i>'
}
},
"columns": [
{
data: null,
class: "userName",
render: function (data, type, row) {
return "<div>" + data.FirstName + " " + data.LastName + "</div></td>";
}
},
{
data: null,
class: "startDate",
render: function (data, type, row) {
var parsedDate = JSON.parse(JSON.stringify(data.StartTime), ToJavaScriptDate);
return "<div>" + parsedDate + "</div></td>";
}
},
//{ 'data': 'User_ID' },
//{ 'data': 'FirstName' },
//{ 'data': 'LastName' },
//{ 'data': 'StartTime' },
],
});
table.on('draw', function () {
var widthofPagination = $('.dataTables_paginate.paging_simple_numbers').width() + 25;
$('#user_session_center_grid_info').css({ width: 'calc(100% - ' + widthofPagination + 'px)' });
});
$("#date_filter_ul.dropdown-menu li a").click(function () {
//debugger;
$('#date_filter_ul').removeClass('show');
$(this).closest('#CategoryFilter').find('.csp-select > span').text("Duration:" + $(this).text());
$('#user_session_center_grid').DataTable().ajax.reload();
});
$("#user_session_center_status_ul.dropdown-menu li a").click(function () {
$('#user_session_center_status_ul').removeClass('open');
$(this).closest('#StatusFilter').find('.csp-select > span').text($(this).text());
$('#user_session_center_grid').DataTable().ajax.reload();
});
});
Here are my controller functions:
public ActionResult UserSessionCenter()
{
if (Session["selectedCustomer"] == null)
{
Session["selectedCustomer"] = 9;
}
int customerId = (int)Session["selectedCustomer"];
var model = new UserSessionHistory();
var daccess = new ApplicationCommon.Ado.SqlDataAccess();
var customerNamesDt = daccess.GetUserNames(customerId);
var customerList = new List<UserSessionData>();
for (var i = 0; i < customerNamesDt.Rows.Count; i++)
{
var userinfo = new UserSessionData();
userinfo.CustomerId = customerNamesDt?.Rows[i]["Customer_Id"].ToString() ?? "";
userinfo.CustomerName = customerNamesDt?.Rows[i]["Customer_Name"].ToString() ?? "";
userinfo.UserId = customerNamesDt?.Rows[i]["User_ID"].ToString() ?? "";
userinfo.UserName = customerNamesDt?.Rows[i]["UserName"].ToString() ?? "";
customerList.Add(userinfo);
}
model.UserInfoList = customerList;
return View(model);
}
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult GetUserSessionHistory()
{
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
if (Request["value1"] != null)
Session["userId"] = Request["value1"];
int pageSize = length != null ? Convert.ToInt32(length) : 0;
try
{
var UserID = Convert.ToInt32(Session["userId"]);
var filterModel = new FilterSessionHistoryModel();
filterModel.UserID = UserID;
filterModel.Skip = int.Parse(start);
filterModel.Take = int.Parse(length);
var fromDate = Request["FromDate"];
var toDate = Request["ToDate"];
filterModel.userSearch = Request["userSearch"];
if (!string.IsNullOrEmpty(fromDate) && !string.IsNullOrEmpty(toDate))
{
filterModel.DateFrom = fromDate;
filterModel.DateTo = toDate;
}
UserService userService = new UserService();
List<ADM_User_Session_History_Result> SessionList = userService.ADM_User_Session_History(filterModel);
int? numberOfRecords = 0;
if(SessionList.Count>0) {
numberOfRecords=SessionList[0].NumberOfRecords;
}
return Json(new { draw = draw, recordsFiltered = (int)numberOfRecords, recordsTotal = (int)numberOfRecords, data = SessionList }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
CustomLogging.LogMessage(ex.Message + "/r/n" + ex.Source + "/r/n" + ex.StackTrace, LogType.Error);
return this.GetJSONObject(false, ex.Message.ToString());
}
}
The hierarchy is like this.
1. The Admin user can use any customer
2. One customer can have many users
3. The table shows the time of log in of the user selected.
The problem is that the list through which the Admin can change the Customer is in the top nav present in _Layout.cshtml where as this data table is in another view. The data changes fine while cahanging the user but I need it to reload or get empty when the customer is changed.

old browsers like 'explorer' keep caching the info from a first ajax call,
you can try to set the cash flag to false and the table will be updated each time
function ReLoadTable() {
$.ajax({
cache: false,
url: 'Your URL',
type: 'POST',
in controller put this attribute
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class HomeController : Controller
{
finally in your Global.asax file add this function
protected void Application_PreSendRequestHeaders(Object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetAllowResponseInBrowserHistory(false);
}

Related

Unable to cast object of type 'System.String' to type 'System.Boolean .Net Core MVC

I refer this tutorial https://github.com/bhrugen/AppointmentScheduler
I did same code but I'm not able to show Get Calendar Data when I running it, It's shows error - Unable to cast object of type 'System.String' to type 'System.Boolean.
My Code is :-
AppointmentApiController.cs :
[HttpGet]
[Route("GetCalendarData")]
public IActionResult GetCalendarData(string doctorId)
{
CommonResponse<List<AppointmentVM>> commonResponse = new CommonResponse<List<AppointmentVM>>();
try
{
if (role == Helper.Patient)
{
commonResponse.dataenum = _appointmentService.PatientsEventsById(loginUserId);
commonResponse.status = Helper.success_code;
}
else if (role == Helper.Doctor)
{
commonResponse.dataenum = _appointmentService.DoctorsEventsById(loginUserId);
commonResponse.status = Helper.success_code;
}
else
{
commonResponse.dataenum = _appointmentService.DoctorsEventsById(doctorId);
commonResponse.status = Helper.success_code;
}
}
catch (Exception e)
{
commonResponse.message = e.Message;
commonResponse.status = Helper.failure_code;
}
return Ok(commonResponse);
}
Script.js :
var routeURL = location.protocol + "//" + location.host;
$(document).ready(function () {
$("#appointmentDate").kendoDateTimePicker({
value: new Date(),
dateInput: false
});
InitializeCalendar();
});
var calendar;
function InitializeCalendar() {
try {
var calendarEl = document.getElementById('calendar');
if (calendarEl != null) {
calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
headerToolbar: {
left: 'prev,next,today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
selectable: true,
editable: false,
select: function (event) {
onShowModal(event, null);
},
eventDisplay:'block',
events: function (frtch, successCallback, failureCallback) {
$.ajax({
url: routeURL + '/api/Appointment/GetCalendarData?doctorId=' + $("#doctorId").val(),
type: 'GET',
dataType: 'JSON',
success: function (response) {
var events = [];
if (response.status === 1) {
$.each(response.dataenum, function (i, data) {
events.push({
title: data.title,
description: data.description,
start: data.startDate,
end: data.endDate,
backgroundColor: "#162466",
textColor: "white",
id: data.id
});
})
}
successCallback(events);
},
error: function (xhr) {
$.notify("Error", "error");
}
});
},
eventClick: function (info) {
getEventDetailsByEventId(info.event);
}
});
calendar.render();
}
}
catch (e) {
alert(e);
}
}
AppointmentService.cs :
public List<AppointmentVM> DoctorsEventsById(string doctorId)
{
return _db.Appointments.Where(x => x.DoctorId == doctorId).ToList().Select(c => new AppointmentVM()
{
Id = c.Id,
Description = c.Description,
StartDate = c.StartDate.ToString("yyyy-MM-dd HH:mm:ss"),
EndDate = c.EndDate.ToString("yyyy-MM-dd HH:mm:ss"),
Title = c.Title,
Duration = c.Duration,
IsDoctorApproved = c.IsDoctorApproved
}).ToList();
}
IAppointmentService.cs :
public List<AppointmentVM> DoctorsEventsById(string doctorId);
Unable to cast object of type 'System.String' to type 'System.Boolean.
You need to make sure the type of IsDoctorApproved in AppointmentVM is bool:
public class AppointmentVM
{
public bool IsDoctorApproved {get;set;}
}
Also,you need to make sure the type of IsDoctorApproved in your database is bool.

Datatables server side processing with mongodb and javascript

Hi I'm having some major issues trying to understand how to datatables to work with server side processing. For some background I'm using a service call Gamesparks to create the backend for a videogame and inside this service they have an implementation of mongodb.
I have an endpoint that fetchs all my users and I can see them in my table but the issue is that I fetch all of them, how can I achieve a pagination?. In the documentation they state that we must put serverSide to true but is not working. I really have no idea on how to proceed I need help.
Gamesparks event to fetch all users
require("LeaderboardMethods");
var playerList = Spark.runtimeCollection("playerList").find({},{"_id":0});
var finalData = [];
while(playerList.hasNext()){
var current = playerList.next();
var playerStats = Spark.runtimeCollection("playerStatistics").findOne({
"playerId":current.playerId
});
var loadedPlayer = Spark.loadPlayer(current.playerId);
var score = getScore(current.playerId);
if(loadedPlayer === null){
var toReturn = {
"playerId": current.playerId,
"displayName": current.displayName,
"email": "DELETED",
"rank": current.rank,
"coins": "DELETED",
"ban": "DELETED",
"score": score
}
finalData.push(toReturn);
} else{
var coins = loadedPlayer.getBalance("COIN");
var toReturn = {
"playerId": current.playerId,
"displayName": current.displayName,
"email": current.email,
"rank":playerStats.rank,
"coins": coins,
"ban": playerStats.isBlocked,
"score":score
}
finalData.push(toReturn);
}
}
Spark.setScriptData("playerList",finalData);
Datatables call
App.getUsers = function(){
var bodyData = {
"#class": ".LogEventRequest",
"eventKey": "GET_PLAYER_DATA",
"playerId": "MY_ID"
}
var table = $('#table1').DataTable({
"dom": "<'row be-datatable-header'<'col-sm-4'l><'col-sm-4'B><'col-sm-4'f>>" +
"<'row be-datatable-body'<'col-sm-12'tr>>" +
"<'row be-datatable-footer'<'col-sm-5'i><'col-sm-7'p>>",
"buttons": [
{
text: 'Edit',
action: function (e, dt, node, config) {
var sel_row = table.rows({
selected: true
}).data();
if (sel_row.length != 0) {
window.location.href = "edit-user.html";
localStorage.setItem("editUser", JSON.stringify(sel_row[0]));
}
}
},
{
text: 'Create',
action: function (e, dt, node, config) {
window.location.href = "create-user.html";
}
},
{
text: 'Delete',
className: 'delete-btn',
action: function (e, dt, node, config) {
var filtered = table.rows({
filter: 'applied',
selected: true
}).data();
// Only open modal when are users selected
if(filtered.length != 0){
$("#proceed-delete").prop('disabled', true)
$("#mod-danger-delete").modal();
if(filtered.length != 1) {
$('#length-users').append(document.createTextNode(filtered.length + " users"));
} else {
$('#length-users').append(document.createTextNode(filtered.length + " user"));
}
$("#delete-confirmation").change(function () {
if ($("#delete-confirmation").val() === "DELETE"){
$("#proceed-delete").prop('disabled', false)
$('#proceed-delete').on('click', function () {
if (filtered.length === 1) {
deleteUserRequest(filtered[0]);
} else {
for (let index = 0; index < filtered.length; index++) {
deleteUserRequest(filtered[index])
}
}
});
}
});
}
}
}, 'selectAll', 'selectNone'
],
"paging":true,
"pageLength":50,
"serverSide":true,
"ajax": {
"data": function (d) {
return JSON.stringify(bodyData);
},
"contentType": "application/json; charset=utf-8",
"url": config.REQUEST_API + '/rs/' + config.API_CREDENTIAL_SERVER + '/' + config.API_SERVER_SECRET + '/LogEventRequest',
"type":"POST",
"dataSrc":function(json){
console.log(json);
$('#loading-row').removeClass('be-loading-active');
return json.scriptData.playerList
},
},
"columns": [
{
data: null,
defaultContent: "<td></td>",
className: 'select-checkbox'
},
{ data: "playerId"},
{ data: "displayName" },
{ data: "email" },
{ data: "score"},
{ data: "rank" },
{ data: "isBlocked" },
{ data: "coins" },
{
"data": null,
"defaultContent": "<button class='btn btn-space btn-primary' onclick='App.click()'>View more</button>"
}
],
"select": {
style: 'multi',
selector: 'td:first-child'
},
}).on('error.dt', function(e, settings, techNote, message){
var err = settings.jqXHR.responseJSON.error;
// GS err
if(err === "UNAUTHORIZED"){
location.href = "pages-login.html";
return true;
} else{
$('#error-container-dt').show();
console.log(message);
return true;
}
});
}
Quick peek into Gamesparks SDK and found this for example:
ListTransactionsRequest
dateFrom Optional date constraint to list transactions from
dateTo Optional date constraint to list transactions to
entryCount The number of items to return in a page (default=50)
include An optional filter that limits the transaction types returned
offset The offset (page number) to start from (default=0)
Now, for paging you need entryCount and offset. First is size of one page, default 50, you can change it. Server returns 'entryCount' no of records.
Offset is the starting record. For example, initial list (1st page) does have 50 records, clicking "Next" button will send request "offset: 51" to the server. And server reply records from 50 (offset) to 100 (offset + entryCount).
var bodyData = {
"#class": ".LogEventRequest",
"eventKey": "GET_PLAYER_DATA",
"playerId": "MY_ID",
"entryCount": entryCount, // you have to send it if you dont like the default value
"offset": offset // gets his value from "NEXT" or "PREV" button
}
Thats how paging works. I'm not able to give more detailed answer as I dont use Gamesparks myself. Hope it gives you least some directon.

Unable retrieving data from server side using custom columns DataTable Plugin

i am trying to retrieving data by custom searching. my code work properly, but when i try to filter some data from the input box. the process, get stuck. Please can anyone tell me what I m forgotting ?
My JQuery
//this work fine retrieving data by only if i search using "Search box"
var dataTableInstance = $("#dataTable").DataTable({
bServerSide: true,
sAjaxSource: 'AccountingMovementsService.asmx/GetAccountingMovements',
"processing": true,
sServerMethod: 'POST',
columns: [
{
'data': 'Payment'
},
{
'data': 'Account',
},
{
'data': 'customer',
}
]
});
//here I make all input box under footer columns (work fine)
$('#dataTable tfoot th').each(function () {
var title = $(this).text();
$(this).html("<input type='text' placeholder='" + title + "' />");
});
//And here i get stuck processing ... and data not come
dataTableInstance.columns().every(function() {
var dataTableColumn = this;
$(this.footer()).find('input').on('keyup change', function () {
dataTableColumn.search(this.value).draw();
});
});
If i use NOT SERVER-SIDE all work fine
My c# code is
[WebMethod]
public void GetAccountingMovements(int iDisplayLength, int iDisplayStart, int iSortCol_0, string sSortDir_0, string sSearch)
{
int displayLength = iDisplayLength;
int displayStart = iDisplayStart;
int sortCol = iSortCol_0;
string sortDir = sSortDir_0;
string search = sSearch;
int filteredCount = 0;
var accountingTransactions = new List<AccountMovement>();
string cs = ConfigurationManager.ConnectionStrings["Sg4DevMaster"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetAccountingTransactions", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "DisplayLength",
Value = displayLength
});
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "DisplayStart",
Value = displayStart
});
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "SortCol",
Value = sortCol
});
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "SortDir",
Value = sortDir
});
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "Search",
Value = search
});
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
AccountMovement am = new AccountMovement();
filteredCount = Convert.ToInt32(rdr["totalCount"]);
am.payment = Convert.ToDouble(rdr["payment"]);
am.Account = Convert.ToDouble(rdr["account"]);
am.Customer = rdr["Customer"].ToString();
accountingTransactions.Add(am);
}
}
var result = new
{
iTotalRecords = GetAccountingMovementsTotalCount(),
iTotalDisplayRecords = filteredCount,
aaData = accountingTransactions
};
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(result));
}
All work fine using "the main search input box" in the DataTable Plugin, but it get stuck when put some data in one of custom input box placed in the footer
Thank for you time!
If you go to my GitHub https://github.com/bindrid/DataTablesServerSide take a look at the c# classes. That is how I take the parameters provided by DataTable and turn it into a usable c# object.
Also listed there is my web method that uses those classes.
Below is the DataTables logic, including your search stuff and it all works.
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"rowCallback": function (row, data) {
if ($.inArray(data.employeeId, selected) !== -1) {
table.row(row).select();
}
},
"infoCallback": function (settings, start, end, max, total, pre) {
var api = this.api();
var pageInfo = api.page.info();
return 'Page '+ (pageInfo.page+1) +' of '+ pageInfo.pages + " ";
},
rowId:"employeeId",
"createdRow": function (row, data, dataIndex) {},
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
],
"select":"multi",
"lengthMenu": [5, [10, 15, 25, 50, -1], [5, 10, 15, 25, 50, "All"]],
"pageLength": 5,
"ajax": {
contentType: "application/json; charset=utf-8",
url: "wsSample.asmx/GetDTDataUnserializedObject",
type: "Post",
data: function (dtParms) {
// notice dtParameters exactly matches the web service
return JSON.stringify({ dtParameters: dtParms });
},
// Data filter is a part of ajax and lets you look at the raw
dataFilter: function (res) {
// You probably know by know that WebServices
// puts your data in an object call d. these two lines puts it
// in the form that DataTable expects
var parsed = JSON.parse(res);
return JSON.stringify(parsed.d);
},
error: function (x, y) {
debugger;
console.log(x);
}
},
order: [[0, 'asc']]
});
// add search boxes to footer
$('#example tfoot th').each(function () {
var title = $(this).text();
$(this).html("<input type='search' placeholder='" + title + "' />");
});
//And here i get stuck processing ... and data not come
table.columns().every(function () {
var dataTableColumn = this;
$(this.footer()).find('input').on('keyup change', function () {
dataTableColumn.search(this.value).draw();
});
});

Present div selected on page refresh?

I am writing an attendance web app using dev-Extrem dx-list (In UI weight). In this attendance we will display all users names in dxlist. and for attendance we just have to select the user. that will enter his name in db. My requirement is if we refresh the page, present should be selected.
My code example is here! ( I am using dev-extreme. )
var listWidget = "";
function getUsers(){
var date = $('#date').val();
var dt = date.split("/");
var dat = dt[2]+"-"+dt[0]+"-"+dt[1];
//alert(dat);
var data = { 'action': 'getUsers', 'date': dat};
$.post("php/users.php", data).success(function (resp) {
//alert(resp);
var users = $.parseJSON(resp);
var selectedItems = [];
var dataSource = new DevExpress.data.DataSource({
store: users,
searchOperation: "contains",
searchExpr: "name",
});
listWidget = $("#simpleList").dxList({
dataSource: dataSource,
editEnabled: true,
height: 400,
allowItemDeleting: false,
itemDeleteMode: "toggle",
showSelectionControls: true,
selectionMode: "multiple",
itemTemplate: function(data, index) {
var result = $("<div>").addClass("product");
$("<img>").attr("src", "images/"+data.id+".jpg").appendTo(result);
var content = $("<div class='content'>").appendTo(result);
$("<div class='findAtt' style='display:none;'>").text(data.attendaceId).appendTo(result);
$("<div class='findId'>").text(data.id).appendTo(content);
$("<div class='findName'>").text(data.name).appendTo(content);
$("<div class='findDep'>").text(data.department).appendTo(content);
$("<div class='findCode'>").text(data.userCode).appendTo(content);
/*var edit = $("<div class='findEdit'>").appendTo(result);
$("<a class='edit' onclick='edit()'>").text("Edit").appendTo(edit);*/
var salary = $("<div class='salary'>").appendTo(result);
$("<div class='findSalary'>").text("Rs."+data.userSalary).appendTo(salary);
return result;
},
onItemSwipe: function(data){
var userId = data.itemData.id;
var userSalary = data.itemData.userSalary;
$('#simpleList').dxList('instance').repaint();
edit(userId, userSalary);
}
}).dxList("instance");
$("#textbox").dxTextBox({
valueChangeEvent: "keyup",
placeholder: "Search",
onValueChanged: function(args) {
dataSource.searchValue(args.value);
dataSource.load();
},
mode: "search"
});
$('.dx-item').click(function(){
var att = $(this).find('.findId').text();
var dep = $(this).find('.findDep').text();
//console.log(this);
attendance(this, att, dep);
$(this).toggleClass('background');
//$(this).find('.dx-checkbox-checked').toggleClass('dx-checkbox-checked');
});
});
}
getUsers();
function attendance(bg, att, dep){
if($(bg).hasClass('background')){
var usersId = att;
var data = { 'action': 'absent',
'userId': usersId
};
$.post("php/users.php", data).success(function (resp) {
});
}else{
var userId = att;
var data = { 'action': 'attendance',
'userId': userId,
'dep': dep
};
$.post("php/users.php", data).success(function (resp) {
//alert(resp);
});
}
}
function edit(userId, userSalary){
$('#eSalary').val(userSalary);
$('#eId').val(userId);
$('#editModal').modal();
}
$('#saveSalary').click(function(){
var userId = $('#eId').val();
var salary = $('#eSalary').val();
var data = { 'action': 'changeSalary', 'userId': userId, 'salary': salary};
$.post("php/users.php", data).success(function (resp) {
$('#editModal').modal('hide');
alert(resp);
//location.reload();
$('#simpleList').dxList('instance').reload();
});
});
$('#depList').change(function(){
var depId = $('#depList option:selected').val();
var data = { 'action': 'getUserDep', 'depId': depId};
$.post("php/users.php", data).success(function (resp) {
//alert(resp);
var users = $.parseJSON(resp);
var selectedItems = [];
var dataSource = new DevExpress.data.DataSource({
store: users,
searchOperation: "contains",
searchExpr: "name"
});
var listWidget = $("#simpleList").dxList({
dataSource: dataSource,
editEnabled: true,
height: 400,
allowItemDeleting: false,
itemDeleteMode: "toggle",
showSelectionControls: true,
selectionMode: "multiple",
itemTemplate: function(data, index) {
var result = $("<div>").addClass("product");
$("<img>").attr("src", "images/"+data.id+".jpg").appendTo(result);
var content = $("<div class='content'>").appendTo(result);
$("<div class='findId'>").text(data.id).appendTo(content);
$("<div class='findName'>").text(data.name).appendTo(content);
$("<div class='findDep'>").text(data.department).appendTo(content);
$("<div class='findCode'>").text(data.userCode).appendTo(content);
var salary = $("<div class='salary'>").appendTo(result);
$("<div class='findSalary'>").text("Rs."+data.userSalary).appendTo(salary);
return result;
}
}).dxList("instance");
$("#textbox").dxTextBox({
valueChangeEvent: "keyup",
placeholder: "Search",
onValueChanged: function(args) {
dataSource.searchValue(args.value);
dataSource.load();
},
mode: "search"
});
$('.dx-item').click(function(){
var att = $(this).find('.findId').text();
var dep = $(this).find('.findDep').text();
//alert(att);
attendance(this, att, dep);
$(this).toggleClass('background');
});
});
});
As far as I understand, you want to save a selection of dxList items on page reload.
If so, I suggest you use the next approach:
Add the selected field for an each item(I mean DB schema). It should be like:
{ id: 1, text: "Bob", selected: true }
Get selected items before list rendering:
var selectedItems = load_from_your_server();
Init a list with the selectedItems option:
$("#list").dxList({
//...
selectedItems: selectedItems
});
Next, add the onSelectionChanged event handler:
$("#list").dxList({
//...
selectedItems: selectedItems,
onSelectionChanged: function(e) {
var listInst = e.component;
e.addedItems.forEach(function(item) {
// update item that was selected
update_your_item_in_db(item.id, {selected: true});
});
e.removedItems.forEach(function(item) {
// update item that was unselected
update_your_item_in_db(item.id, {selected: false});
});
}
});
I've create the small sample http://jsfiddle.net/vvh70no2/5/ that illustrates my idea. I've used an Array, not a real db.

Kendo UI Angular Upload / Kendo Grid integration

Ok, here are the Versions:
Kendo UI v2014.3.1119
AngularJS v1.3.6
jQuery v#1.8.1 jquery.com
The issue is the following: I have a kendo upload that should populate a grid after a excel file is read. I'm using Kendo UI Angular Directives. Here are some key pieces of code:
Upload Html
<input name="files"
type="file"
kendo-upload
k-async="{ saveUrl: '{{dialogOptions.ImportUrl}}', autoUpload: false, batch: true }"
k-options="{localization: {uploadSelectedFiles: '{{messages.Global_Button_Import}}'}}"
k-error="onImportError"
k-select="onSelect"
k-success="onImportSuccess" k-multiple="false" />
Grid Html
<div kendo-grid="grid" k-options="gridOptions" k-ng-delay="gridOptions" k-rebind="gridOptions" >
</div>
Key pieces on the controller
angular.module('global').controller('ImportResultsController', [
'$scope', 'BaseApi', 'ImportResultsService', 'GridUtil', '$http', '$q', '$timeout',
function ($scope, BaseApi, ImportResultsService, GridUtil, $http, $q, $timeout) {
$scope.gridOptions;
$scope.gridColumns;
$scope.results = new kendo.data.ObservableArray([]);
//These columns should come from the server, right now are harcoded
$scope.getGridColumns = function () {
$scope.gridColumns = [
{ field: "Zone", width: 70, title: "Zone", template: "" },
{ field: "Aisle", width: 70, title: "Aisle", template: "" },
{ field: "Rack", width: 70, title: "Rack", template: "" },
{ field: "Shelf", width: 70, title: "Shelf", template: "" },
{ field: "Bin", width: 70, title: "Bin", template: "" },
//{ field: "DateEffectiveFrom", width: 70, title: "Date" },
{ field: "BinStatus", width: 70, title: "BinStatus", template: "" }
];
}
$scope.getClientGridOptions = function(columns, data, pageSize) {
var gridOptions = {
sortable: true,
dataSource: {
data: data,
pageSize: pageSize
},
selectable: 'row',
columns: columns,
pageable: {
pageSize: pageSize,
refresh: false,
pageSizes: [10, 20, 30],
messages: $.kendoMessages
},
};
return gridOptions
}
$scope.onImportSuccess = function (e) {
var files = e.files;
if (e.operation == "upload") {
console.log(files);
if (e.XMLHttpRequest.response != "") {
var model = $.parseJSON(e.XMLHttpRequest.response); //This step does not fail, model return is always filled
$scope.results = new kendo.data.ObservableArray([]);
for (var i = 0; i < model.Data.length; i++) {
$scope.results.push(model.Data[i]);
}
$scope.gridOptions = $scope.getClientGridOptions($scope.gridColumns, $scope.results, 10);
//$scope.grid.dataSource.data($scope.results); //This does not work
$scope.isDataReady = true;
// $("#grid").data("kendoGrid").dataSource.data($scope.results) //This does not work
// $scope.grid.refresh(); //This does not work
$scope.$apply()
}
}
}
}]);
The issues vary. Sometimes I get the data bound until the second uploaded file, and after the third time, I start receiving 'Cannot read property 'get' of undefined ' errors. When this second error happens, the bind works, but the error is present. Do you have any idea of what could it be?
In case of you need the url for the upload, here's the method. Is an MVC .net application. Since I always get the response correctly and it's a Json Array, I believe there's no issue there, but here's anyways.
dialogOptions.ImportUrl = LoadImportedBinLocations
MVC Controller
[System.Web.Http.HttpPost]
public ActionResult LoadImportedBinLocations(IEnumerable<HttpPostedFileBase> files)
{
bool success = false;
var importHistory = new PartsImportHistory();
List<dynamic> data = null;
try
{
//int divisor = 0;
//var y = 5 / divisor;
if (files != null)
{
using (var client = new ServiceLocator<IPartsService>())
{
foreach (var file in files)
{
string extension = Path.GetExtension(file.FileName);
bool isExcelFile = extension == ".xls" || extension == ".xlsx";
if (isExcelFile)
{
var filePath = UploadAttachment(file);
//importHistory = client.Service.SavePartsImportHistory(new PartsImportHistory
//{
// CreatedByName = CurrentContext.UserDisplayName,
// CreatedByUserID = CurrentContext.UserId,
// PartsImportStatus = (int)DMSModel.EnumStore.PartsImportStatus.InProgress,
// FilePath = filePath
//});
data = new List<dynamic>
{
new { Zone = "A", Aisle = "02", Rack = "06", Shelf = "20", Bin = "D", DateEffectiveFrom = DateTime.UtcNow, BinStatus = "Unblocked", IsValid= true, ImportError ="" },
new { Zone = "B", Aisle = "02", Rack = "06", Shelf = "10", Bin = "D", DateEffectiveFrom = DateTime.UtcNow, BinStatus = "Blocked", IsValid=false, ImportError="Zone does not Exist" }
};
success = true;
}
else
{
throw new Exception(WarpDMS.Globalization.Resources.PartsAdmin_ImportParts_ErrorFileFormat);
}
}
}
}
return Json(new { success = success, Data = data });
}
catch (Exception ex)
{
return Content(ex.Message ?? ex.ToString());
}
}
private string UploadAttachment(HttpPostedFileBase item)
{
string path = string.Empty;
string internalFileName = string.Empty;
string basePath = ConfigManager.ATTACHMENTS_PATH;
if (item != null && item.ContentLength > 0)
{
internalFileName = System.IO.Path.ChangeExtension(Guid.NewGuid().ToString(), System.IO.Path.GetExtension(item.FileName));
path = Path.Combine(basePath, internalFileName);
item.SaveAs(path);
}
return Path.Combine(basePath, internalFileName).Replace('\\', '/');
}

Categories