Kendo pager will not reset back to the first page - kendo-ui

I have a made a kendo datasource which makes a call out to my api, I have it limited to make pages of 10's. My problem is that the pager will not set back to the first page. For example, when I make a call and to my api and receive 50 results, I will have 5 pages of 10 items each. I select to go to the fifth page which, I then make another call and only receive 10 items which makes one page. However then the cal completes I am still on the 5th page; it will not reset to the first page.
var dataSource = new kendo.data.DataSource({
page:1, << From what I read this is suppose to do the job
pageSize: 10,
transport: {
read: {
type: "POST",
url: location + "/api/ContentSearch/SearchRequest",
contentType: 'application/json',
beforeSend: function (req) {
req.setRequestHeader("Authorization", "Bearer " + token);
}
},
parameterMap: function (option, operation) {
return JSON.stringify(query);
}
},
change: function (e) {
var data = this.data();
$("#searchButton").prop("disabled", false);
$("#loadingGif").hide();
//kendoPager.page(1); << does not work
switch (data.length) {
case 0:
FeedBackMessage("No result found");
break;
case 500:
FeedBackMessage("Please check or refine the search");
break;
default:
$('#pager').show();
$('#descriptionColumn').show();
$("#listView").show();
$("#keyWordText").val("").data("kendoDropDownList").text("");
$("#searchText").val("");
}
return data;
},
error: function (e) {
$("#loadingGif").hide();
ErrorHandler(e.sender.transport.options.read.url, e.xhr.status, e.xhr.statusText, "Kendo datasource was not binded to the WebApi response", "", true);
}
});
function SubmitSearch(e) {
e.preventDefault();
query = {
SearchText: $("#searchText").val(),
KeywordText: generalContentKeywords.text(),
GlobalSearch: true
};
if (query.SearchText === "" && query.KeywordText === "Select Category") {
FeedBackMessage("Please enter a value");
}
else {
if (query.KeywordText === "Select Category") {
query.KeywordText = "";
}
$.when(TokenForWebApi()).then(function (adalToken) {
token = adalToken;
$('#pager').hide();
$('#descriptionColumn').hide();
$("#listView").hide();
$("#searchButton").prop("disabled", true);
$("#loadingGif").show();
dataSource.read();
});
}
};
var kendoPager = $("#pager").kendoPager({
dataSource: dataSource,
}).data("kendoPager");

I went around this issue, by changing my submit function to see if the datasource has any data, and if it find that it does it reset set the page back to one. I am guessing that my previous code, I was trying to set a page value before the datasource had any values to page.
function SubmitSearch(e) {
e.preventDefault();
query = {
SearchText: $("#searchText").val(),
KeywordText: generalContentKeywords.text(),
GlobalSearch: true
};
if (query.SearchText === "" && query.KeywordText === "Select Category") {
FeedBackMessage("Please enter a value");
}
else {
if (query.KeywordText === "Select Category") {
query.KeywordText = "";
}
$.when(TokenForWebApi()).then(function (adalToken) {
if (dataSource._pristineData.length) {
kendoPager.page(1);
}
token = adalToken;
$('#pager').hide();
$('#descriptionColumn').hide();
$("#listView").hide();
$("#searchButton").prop("disabled", true);
$("#loadingGif").show();
dataSource.read();
});
}
};

Related

asp.net mvc not getting value from ajax when converting data into json.stringify

I am using a event handler that checks if the product id or name already exist. But my problem is when I am using JSON.stringify() my C# controller does not receive the data from the ajax call,.
// check if Product name already exist
$('#productName').bind('keyup blur', function () {
// check if input is empty
if ($(this).val().length > 0) {
var data = JSON.stringify({
value: $(this).val(),
fieldName: 'productName'
});
$.ajax({
type: "post",
url: '/Product/ValidateProductDetailsExist',
contenttype: "application/json; charset=utf-8",
datatype: "json",
data: data,
context: this,
success: function (result) {
if (result === true) {
// append error message
// check if error message already exist
if ($('#errorprodcutName').length === 0) {
var errormessage = '<div class="col-md-offset-2"><span id = "errorprodcutName" class="validation-error-message">Product name already exist</span></div >';
$('.form-group:nth-child(2)').append(errormessage);
}
$(this).focus();
//disables the save button
$('#btnSaveProduct').prop('disabled', true);
}
else {
// check if error message already exist
if ($('#errorprodcutName').length > 0) {
$('#errorprodcutName').remove();
}
//enables the save button
$('#btnSaveProduct').prop('disabled', false);
}
},
error: function () {
alert("unable to request from server");
}
});
}
});
When I use debugger to check the value, it is null. I don't see any errors that displays in the console as well. Can anyone please explain to me why it is not working.
public JsonResult ValidateProductDetailsExist(string value, string fieldName)
{
using (POSEntities3 db = new POSEntities3())
{
bool isExist = false;
switch (fieldName)
{
case "productId":
var dataItemProductId = db.Products.Where(product => product.product_id == value).SingleOrDefault();
isExist = (dataItemProductId != null);
break;
case "productName":
var dataItemProductName = db.Products.Where(product => product.name == value).SingleOrDefault();
isExist = (dataItemProductName != null);
break;
}
return Json(isExist, JsonRequestBehavior.AllowGet);
}
}

Bootstrap Selectpicker not refreshing

When a user clicks the edit icon the contents of a selectpicker are updated then refreshed. Then the selectpicker's value is updated, then refreshed again, but for some reason it is not updating with the selected value.
Everything works fine when I manually enter in the the same code in the console.
$('#IncWidgetId').val(864)// the value used when breaking in console
$('#IncWidgetId').selectpicker('refresh')
I have ensured that the selectpicker is updated with the new option values along with confirming the deferred is firing in the proper order.
As a double check, I also have separated the .selectpicker('refresh') to make sure it didn't try to fire before the option was selected due to async, but it is still not updating the selectpicker with the selected value.
$(document).on('click', '[id^=EditWidgetId-]', function () {
var id = $(this).attr('id').split('-')[1];
var mfg = $(this).data('mfg');
var widgetid = $(this).data('widgetid ');
var mfgSelect = $('input[name=mfg][value="' + mfg + '"]');
mfgSelect.prop('checked', true);
$.when(LoadWidgets(mfg)).then(function () {
console.log('then function');
$('#IncWidgetId').val(widgetid );
}).done(function () {
console.log('done function');
$('#IncWidgetId').selectpicker('refresh');
});
$('#modalWidgetNew').modal('show');
});
function LoadWidgets(mfg) {
var r = $.Deferred();
console.log('before ajax');
r.resolve($.ajax({
url: '/Widgets/FilterWidgetsDropdown',
type: 'GET',
cache: false,
data: { mfg: mfg },
success: function (partial) {
$('#IncWidgetDDArea').html(partial);
$('#IncWidgetId').selectpicker('refresh')
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internel Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
})).done(function () {
console.log('after ajax');
return r.promise();
});
}
What am I missing?
There was such an issue in old versions of this plugin.
Try to destroy it and initialize again. Something like this:
$('#IncWidgetId').selectpicker('destroy');
$('#IncWidgetId').selectpicker();

Telerik Kendo MVC Grid Validation Always Fails

I am tearing my hair out with this...!
I have a telerik kendo mvc ui grid widget using an Inline gridedit mode. When the user adds a new entry to the grid (by way of a custom dropdown edit control), I want it to validate that this entry is not already present in the grid.
I have an MVC controller action that does this and returns True or False accordingly. This works perfectly. Here is the validator javascript code I am using.
(function ($, kendo) {
$.extend(true, kendo.ui.validator, {
rules: {
bedQuantity: function (input, params) {
if (input.is("[name='Quantity']") && input.val() <= 0) {
input.attr("data-bedQuantity-msg", "Quantity must be 1 or more");
return false;
}
return true;
},
bedExists: function(input, params) {
if (input.is("[name='BedType']")) {
var model = {
PropertyId: #Model.Id,
BedTypeId: input.val()
};
var url = "/Property/ValidateBedTypeExists";
input.attr("data-val-bedExists-requested", true);
$.ajax({
type: "POST",
url: url,
traditional: true,
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
success: function(data) {
return data === false;
},
fail: function(data) {
return false;
}
});
} else {
return true;
}
}
},
messages: {
bedQuantity: function (input) {
return input.attr("data-val-bedQuantity");
},
bedExists: function(input) {
return "This bed type already exists";
}
}
});
})(jQuery, kendo);
No matter whether the ajax call returns true or false, the validator always flags the entry as invalid.
You can give the html attribute for the kendoDropdownList as required like this
#(Html.Kendo().DropDownList()
.DataValueField("")
.DataTextField("")
.Name("")
.HtmlAttributes(new { required ="required" })
.OptionLabel("- Select a type - ")
.Filter(FilterType.Contains)
)
Try this..

Kendo Treeview expand and checkbox not working after new value was passed in from a dropdown list

new to stackoverflow and implementing treeview. I'm having an issue where whenever I select a different value from my dropdown list that would populate my treeview the expand and checkbox is not working anymore. But the first time works.
So I have ajax call that would grab a parameter from a dropdown list to return JSON data to populate my tree. Here's my code. I've been pounding my head for this error and I've also tried some solution in the kendo ui documentation but it just doesn't work. Really need some help. Thank you!
Here's my code:
dataB1 = #Html.Raw(Json.Encode(ViewData["branchList"]));
reloadNewBranch = #Html.Raw(Json.Encode(ViewData["reloadNewBranch"]));
$('#comboNewBranch').kendoAutoComplete({
dataSource: dataB2,
placeholder: "Enter branch name...",
value: reloadNewBranch
});
//Create TreeView
function onChange(e) {
$("body").css("cursor", "progress");
$('#hiddenPackageArray').val('');
document.getElementById("textTestpassId").innerHTML = 'At least one(1) template must be selected.';
$('#treeview').empty();
$.ajax({
url: '#Url.Action("LoadOldBranchTemplates", "Home")',
data: { oldBranchName: $("#comboOldBranch").data("kendoAutoComplete").value() },
dataType: "json"
}).done(function (result, textStatus, jqXHR) {
var viewModel = new kendo.data.HierarchicalDataSource({
data: result,
schema: {
model: {
id: "Id",
hasChildren: true,
children: "Templates"
}
}
});
$("#treeview").kendoTreeView({
loadOnDemand: false,
checkboxes: {
checkChildren: true
},
check: onCheck,
dataSource: viewModel,
dataTextField: ["TestPassName", "DisplayName"]
})
// gathers IDs of checked nodes
function checkedNodeIds(nodes, checkedNodes) {
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
checkedNodes.push(nodes[i].Id);
let filtered = checkedNodes.filter(function (listOfId) {
return listOfId != null;
});
$('#hiddenPackageArray').val(filtered);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}
// show checked node IDs on datasource change
function onCheck(e) {
console.log("I'm in onSelect function");
var checkedNodes = Array();
var treeView = $("#treeview").data("kendoTreeView");
var message = String();
checkedNodeIds(treeView.dataSource.view(), checkedNodes);
console.log("Checkbox changed :: " + this.text(e.node));
if (checkedNodes.length > 0) {
message = checkedNodes.join(" ");
} else {
message = "No package(s) are selected.";
$('#hiddenPackageArray').val('');
}
$("#result").html(message);
}
$("body").css("cursor", "default");
})
.fail(function (xmlHttpRequest, textStatus, errorThrown) {
$('#mainDiv').append('<p>Status: ' + textStatus + '</p>');
$('#mainDiv').append('<p>Error: ' + errorThrown + '</p>');
$('#mainDiv').append('<p>' + xmlHttpRequest + '</p>');
});
};

Backbone collection fetch error with no information

I have a strange problem with the fetch of a backbone collection I am working with. In one particular instance of my code I perform a fetch (exactly how I do it in other areas of the code which all work fine), the fetch never seems to make it to the server and the developer tools shows the request as red with the word (canceled) in the status/text field.
I've walked this through into the backbone sync method and I see the $.ajax being built and everything looks fine. Has anyone run into this problem?
here is my code if it helps, this is a function that calls two .ashx services to first check for a file's existence then to open it. The part that isn't working for me is the "me.collection.fetch().
openDocument: function () {
var me = this,
fileId = me.model.get('id'),
userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;
//hide tooltip
me.hideButtonTooltips();
// Check for file existance
$.ajax({
url: fileCheck
})
.done(function (data) {
if (data && data === "true") {
document.location.href = fileRequest;
me.collection.fetch();
} else if (!!data && data === "false") {
"This file is no longer available.".notify('error');
}
})
.fail(function (data) {
"Something went wrong during the File Existance check".notify('error');
"Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
});
},
my collection:
// docsCollection.js - The collection of ALL the documents available to a given user
// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({
model: Dashboard.Models.DocumentUploadModel,
url: function () {
return 'apps/docs/Docs/' + this.userId;
},
initialize: function (options) {
this.userId = options.userId;
this.deferredFetch = this.fetch();
},
comparator: function (model) {
return -(new Date(model.get('expirationDate')));
},
getDaysSinceViewedDocuments: function () {
return this.filter(function (model) {
return model.get('daysSinceViewed') !== null;
});
},
getNewDocuments: function () {
return this.filter(function (model) {
return model.get('isNew');
});
},
getExpiredDocuments: function () {
return this.filter(function (model) {
return model.get('isExpired');
});
}
});
and my model:
Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
defaults: {
fileArray: [],
name: '',
description: '',
accesses: [],
tags: [],
expirationDate: ''
},
initialize: function () {
this.set({
userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
}, { silent: true });
function buildExpirationDate() {
var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());
return dateString;
}
},
firstFile: function () {
return this.get('fileArray')[0];
},
validate: function (attributes) {
var errors = [];
if (attributes.name === '' || attributes.name.length === 0)
errors.push({
input: 'input.txtName',
message: "You must enter a name."
});
if (attributes.description === '' || attributes.description.length === 0)
errors.push({
input: 'textarea.taDescription',
message: "You must enter a description."
});
if (errors.length > 0)
return errors;
return;
},
sync: function (method, model, options) {
var formData = new FormData(),
files = model.get("fileArray"),
$progress = $('progress'),
success = options.success,
error = options.error;
// Nothing other than create or update right now
if (method !== "create" && method !== "update")
return;
// Build formData object
formData.append("name", model.get("name"));
formData.append("description", model.get("description"));
formData.append("accesses", model.get("accesses"));
formData.append("tags", model.get("tags"));
formData.append("expirationDate", model.get("expirationDate"));
formData.append("userId", model.get("userId"));
formData.append("isNew", model.isNew());
// if not new then capture id
if (!model.isNew())
formData.append('id', model.id);
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
if (success)
success();
} else {
if (error)
error();
}
}
if ($progress.length > 0) {
xhr.upload.onprogress = function (evt) {
var complete;
if (evt.lengthComputable) {
// Do the division but if you cant put 0
complete = (evt.loaded / evt.total * 100 | 0);
$progress[0].value = $progress[0].innerHTML = complete;
}
}
}
xhr.send(formData);
},
upload: function (changedAttrs, options) {
this.save("create", changedAttrs, options);
}
});
You're assigning a value to document.location.href before you try to fetch your collection:
document.location.href = fileRequest;
me.collection.fetch();
Changing document.location.href will change the whole page and in the process, any currently running JavaScript will get shutdown so I wouldn't expect your me.collection.fetch() to ever get executed.

Resources