Kendo UI Treelist rows disappears after editing - asp.net-mvc

I use Kendo UI in ASP .NET MVC app. I have Kendo Treelist. Sometimes, after editing a row, all rows disappear, and I see only root element without child rows. Is it Kendo bug?Or I can prevent it? And when rows have disappeared, I refresh page, do the same changes and save treelist - the treelist works correctly.
var parsedXmlDataInJson = #Html.Raw(#ViewBag.XmlData); //jsonarray data
$( document ).ready(function() {
});
function ShowMessage(message,timeout) //пока сообщению пользователю в левом верхнем углу
{
var divMessage = $('#toggler');
if(divMessage.css('display') != 'none')
{
divMessage.clearQueue();
divMessage.stop();
divMessage.css('display','none');
}
if (timeout == 0)
divMessage.text(message).toggle('slow');
else
divMessage.text(message).toggle('slow').delay(timeout).toggle('slow');
}
var treelistds = new kendo.data.TreeListDataSource({ //CRUD for dataSource
transport: {
read: function(e) {
e.success(parsedXmlDataInJson);
},
update: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
value = updatedItem;
return false;
}
});
e.success();
},
create: function(e) {//Works for root element when editing only once - it's broke my treelist.
e.data.Id = GetId();
parsedXmlDataInJson.push(e.data);
e.success(e.data);
},
destroy: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
parsedXmlDataInJson.splice(indx, 1);
}
});
e.success();
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: false,
schema: {
model: {
id: "Id",
parentId: "parentId",
fields: {
Id: {
type: "number",
editable: true,
nullable: false
},
parentId: {
field: "parentId",
nullable: true
}
}
}
}
});
$("#treeList").kendoTreeList({
resizable: true,
dataSource: treelistds,
toolbar: ["create"],
columns: [{
field: "typeAndAttributes",
width:400
}, {
field: "text",
title: "Текст",
}, {
field: "cData",
title: "CDATA",
}, { //my custom command
command: ["edit", "destroy", "createchild", {
name: "commentOut",
text: "commentOut",
click: function(e) {
var dataItem = this.dataItem($(e.target).closest("tr")); ///my custom command
dataItem.commentedOut = !dataItem.commentedOut;
var isCommentedOut = dataItem.commentedOut;
var childNotes = this.dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) //
{
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
//обновляем цвет и текст кнопок у всех элементов вызывая dataBound
$("#treeList").data("kendoTreeList").refresh();
},
}, ]
}],
messages: {
commands: {
edit: "Изменить",
destroy: "Удалить",
createchild: "Добавить"
}
},
dataBound: function(e) {
this.autoFitColumn(3);
Databound(e.sender, e.sender.table.find("tr"));
},
editable: true,
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html()),
window: {
width:800
}
},
edit: function(e) { //invokes when popup open
$("#date").kendoDateTimePicker({
});
$("#cDataEditor").kendoEditor({
tools: [
"formatting", "bold", "italic", "underline", "insertUnorderedList",
"insertOrderedList", "indent", "outdent", "createLink", "unlink"
],
resizable: {
content: true,
toolbar: true,
max:350
}
});
//my custom logic. Popup contains many fileds splitted from one model field
if (!e.model.isNew()) { //split typeAndAttrubites to popup's fileds
var fileds = e.model.typeAndAttributes.split(';').
filter(function(v) {
return v !== ''
});
e.container.find("#type").val(fileds[0]);
var length = fileds.length;
for (i = 1; i < length; i++) {
var keyAndValue = fileds[i].split('=');
if (keyAndValue[0] != "id")
e.container.find("#" + keyAndValue[0].trim()).val(keyAndValue[1].trim());
else
e.container.find("#xmlId").val(keyAndValue[1].trim());
}
}
},
save: function(e) { //invokes when saving
var splitter = "; ";
var inputValue = $("input[id='type']").val().trim();
if (e.model.type !== undefined) {
e.model.typeAndAttributes = e.model.type;
} else {
e.model.typeAndAttributes = inputValue;
}
var allInputs = $(":input[data-appointment=attributes]");
allInputs.each(function(index, input) { //collect inputs in one filed
var attrName;
var attrValue;
if (input.id != "id") {
attrName = input.id;
e.model[attrName];
} else {
attrName = "id";
attrValue = e.model["xmlId"];
}
//значение изменили и оно не пустое
if (attrValue !== undefined && attrValue !== "") {
if (attrValue == false)
return true;
e.model.typeAndAttributes += splitter + attrName + "=" + attrValue;
}
//my custom logic
else if (input.value.trim() && input.value != "on") {
e.model.typeAndAttributes += splitter + attrName + "=" + input.value.trim();
}
})
}
});
//рекурсивно помечаем ряды как закомментированные или нет
function SetChildrenIsCommentedOut(dataItem, isCommentedOut) {
var childNotes = $("#treeList").data("kendoTreeList").dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) {
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
}
//Раскрашивает строки соответственно значению закомментировано или нет
function Databound(sender, rows) {
rows.each(function(idx, row) {
var dataItem = sender.dataItem(row);
if (dataItem.commentedOut) {
//обозначаем ряд как закомментированный
$(row).css("background", "#DCFFE0");
$(row).find("[data-command='commentout']").html("Раскомментировать");
} else {
//обозначаем ряд как незакомментированный
$(row).css("background", "");
$(row).find("[data-command='commentout']").html("Закомментировать");
}
})
}
});
var currentId = 0;
function GetId() { //генерирование Id для новых записей
var dataSource = $("#treeList").data("kendoTreeList").dataSource;
do {
currentId++;
var dataItem = dataSource.get(currentId);
} while (dataItem !== undefined)
return currentId;
}

Related

Camera doesn't work after compilation

I use Ionic Framework.
Camera works perfectly in Ionic View. But it doesn't work after compilitaion on iOS.
Please, help to find out what is the problem.
Camera code in services.js:
app.factory('FileService', function() {
var images;
var IMAGE_STORAGE_KEY = 'dav-images';
function getImages() {
var img = window.localStorage.getItem(IMAGE_STORAGE_KEY);
if (img) {
images = JSON.parse(img);
} else {
images = [];
}
return images;
};
function addImage(img) {
images.push(img);
window.localStorage.setItem(IMAGE_STORAGE_KEY, JSON.stringify(images));
};
return {
storeImage: addImage,
images: getImages
}
});
app.factory('ImageService', function($cordovaCamera, FileService, $q, $cordovaFile) {
function optionsForType(type) {
var source;
switch (type) {
case 0:
source = Camera.PictureSourceType.CAMERA;
break;
case 1:
source = Camera.PictureSourceType.PHOTOLIBRARY;
break;
}
return {
quality: 90,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: source,
allowEdit: false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation:true
};
}
function saveMedia(type) {
return $q(function(resolve, reject) {
var options = optionsForType(type);
$cordovaCamera.getPicture(options).then(function(imageBase64) {
FileService.storeImage(imageBase64);
});
})
}
return {
handleMediaDialog: saveMedia
}
});
Camera code in controllers.js:
app.controller('CameraController', function($scope, $cordovaDevice, $cordovaFile, $ionicPlatform, $cordovaEmailComposer, $ionicActionSheet, ImageService, FileService) {
$ionicPlatform.ready(function() {
$scope.images = FileService.images();
$scope.$apply();
});
$scope.addMedia = function() {
$scope.hideSheet = $ionicActionSheet.show({
buttons: [
{ text: 'Take photo' },
{ text: 'Photo from library' }
],
titleText: 'Add images',
cancelText: 'Cancel',
buttonClicked: function(index) {
$scope.addImage(index);
}
});
}
$scope.addImage = function(type) {
$scope.hideSheet();
ImageService.handleMediaDialog(type).then(function() {
$scope.$apply();
});
}
$scope.sendEmail = function() {
if ($scope.images != null && $scope.images.length > 0) {
var mailImages = [];
var savedImages = $scope.images;
for (var i = 0; i < savedImages.length; i++) {
mailImages.push('base64:attachment'+i+'.jpg//' + savedImages[i]);
}
$scope.openMailComposer(mailImages);
}
}
$scope.openMailComposer = function(attachments) {
var bodyText = '<html><h2>My Images</h2></html>';
var email = {
to: '',
attachments: attachments,
subject: 'Devdactic Images',
body: bodyText,
isHtml: true
};
$cordovaEmailComposer.open(email, function(){
console.log('email view dismissed');
}, this);
}
});
To resolve this problem you need to compile an app with XCode.
After XCode compilation camera works correctly.
Probably, the problem with camera was caused by Ionic compilation.

Kendo grid footer template sum issue

var dataSourceDashboard = new kendo.data.DataSource({
pageSize: 20,
type: "json",
transport: {
read: function (operation) {
if (navigator.onLine) {
$.ajax({
url: '/Home/Dashboard_Read/',
type: "GET",
dataType: "json",
success: function (response) {
try
{
localStorage.setItem("Dashboard_Read", JSON.stringify(response));
}
catch (domException)
{
if (domException.name === 'QuotaExceededError' ||
domException.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
// Fallback code comes here.
$("#progressMsgError").html("Cannot save the data for offline use, please clear the cache, or call administrator!");
$('#myModalError').modal('show');
}
}
operation.success(response);
BindSitesCombo(response);
//// initial sync of data
//var cashedDataBaseJson = [];
//var cashedDataBase = localStorage.getItem("cashedDataBase");
//if (cashedDataBase != null || cashedDataBase != undefined) {
// cashedDataBaseJson = JSON.parse(cashedDataBase);
// if (cashedDataBaseJson.length > 0) {
// syncInitialData(cashedDataBaseJson);
// localStorage.setItem("cashedDataBase", JSON.stringify(cashedDataBaseJson));
// }
//}
//else
//{
// syncInitialData(response);
// localStorage.setItem("cashedDataBase", JSON.stringify(response));
//}
var cashedDataBase = localStorage.getItem("cashedDataBase");
if (cashedDataBase == null || cashedDataBase == undefined) {
localStorage.setItem("cashedDataBase", JSON.stringify(response));
}
else {
var cashedDataBaseJson = [];
var cashedDataBase = localStorage.getItem("cashedDataBase");
if (cashedDataBase != null || cashedDataBase != undefined) {
cashedDataBaseJson = JSON.parse(cashedDataBase);
var i = response.length;
while (i--)
{
var ifsiteisinthelist = contains(cashedDataBaseJson, response[i]);
if (ifsiteisinthelist == false)
{
cashedDataBaseJson.push(response[i]);
}
}
localStorage.setItem("cashedDataBase", JSON.stringify(cashedDataBaseJson));
}
}
rempvesyncedlinks();
},
error: function (response)
{
window.location.href = "/account/login";
}
});
}
else {
var cashedData = localStorage.getItem("Dashboard_Read");
if (cashedData != null || cashedData != undefined) {
//if local data exists load from it
var data = JSON.parse(cashedData);
operation.success(data);
BindSitesCombo(data);
rempvesyncedlinks();
}
}
}
},
schema: {
model: {
id: "SiteID",
}
},
//change: function (e) {
// $.each(dataSourceDashboard.data(), function (index, value) {
// $('#cmbAllSites')
// .append($("<option></option>")
// .attr("value", value.SiteID)
// .text(value.SiteName));
// });
//}
change: function (e) {
rempvesyncedlinks();
},
aggregate: [
{ field: "DailyTotalFormated", aggregate: "sum" },
{ field: "WeeklyTotalFormated", aggregate: "sum" },
{ field: "WeeklySiteTotalFormated", aggregate: "sum" },
{ field: "WeeklyGoal", aggregate: "sum" }
],
});
$(function () {
$("#gridDashboard").kendoGrid({
dataSource: dataSourceDashboard,
filterable: false,
groupable: false,
toolbar: false,
pageable: {
change: function (e) {
rempvesyncedlinks();
}
},
sortable: true,
height: 600,
columns: [
{ field: "SiteName", title: "MY COMPANIES", template: '#=SiteName#',footerTemplate: "Total " },
{ field: "DailyTotalFormated", title: "MY DAILY TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklyTotalFormated", title: "MY WEEKLY TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklySiteTotalFormated", title: "WEEKLY SITE TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklyGoal", title: "WEEKLY SITE GOAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "", title: "SYNC", template: "# if (isSynced == true) { #" +
"<div style='width: 130px;margin: auto;'><img src='/images/ready.png' alt='Up-to-date' /><div style='font-size:15px; font-weight:bolder; float: right;'>Ready</div></div>" +
"# } else { #" +
"<div style='width: 130px;margin: auto;'><img src='/images/pleasesync.png' alt='Up-to-date' /><div style='font-size:15px; font-weight:bolder; float: right;'>Please Sync</div></div>" +
"# } # <a id='syncforoffline#=SiteID#' href='##' onclick='syncDataForSite(#=SiteID#);return false;'>Sync for offline</a>"
},
{ field: "SiteLogo", title: " ", hidden : true },
],
editable: false
});
$("#cmbAllSites").change(function ()
{
var di = dataSourceDashboard.data()[this.selectedIndex - 1];
setSiteID(di.SiteID, di.SiteLogo, di.SiteName);
});
});
Footer sum is not calculated
What is wrong in this code, why does the total show last row by default?
I fixed the issue. I am just adding:
model: {
id: "SiteID",
fields: {
SiteName: { type: "string" },
DailyTotalFormated: { type: "number" },
WeeklyTotalFormated: { type: "number" },
WeeklySiteTotalFormated: { type: "number" },
WeeklyGoal: { type: "number" }
}
}

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

Keep impromptu "up" while performing a jquery Ajax/MVC post

Is there a way to keep the impromptu dialog box displayed during a post?
Here's the javascript code
$('#linkPostTest').click(function() {
openprompt();
});
function openprompt() {
var temp = {
state0: {
html: 'Are you sure you want to post?<br />',
buttons: { Yes: true, No: false },
focus: 1,
submit: function(v, m, f) {
if (v) {
var form = $('frmPostTest');
$.ajax(
{
type: 'POST',
url: '/Path/TestPost',
data: form.serialize(),
success: function(data) {
// I realize I could check "data"
// for true...just have not
// implemented that yet....
$.prompt.goToState('state1');
//$.prompt('Test was successful!');
},
error: function() {
$.prompt.goToState('state2');
//$.prompt('Test was not successful.');
}
}
);
return true;
}
else {
//$.prompt.goToState('state1'); //go forward
return false;
}
}
},
state1: {
html: 'Test was successful!',
buttons: { Close: 0 },
focus: 0,
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
},
state2: {
html: 'Test was not successful.<br />',
buttons: { Close: 0 },
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
}
};
$.prompt(temp);
}
The controller does this
[AcceptVerbs(HttpVerbs.Post)]
public bool TestPost()
{
// runs some code that saves some data...
// this works fine
bool updated = functionThatSavesCode();
return updated;
}
After I click Yes when the 'Are you sure you want to post?' impromptu dialog is displayed... it disappears...How can I make it stay displayed?
OK got it to work...I'm really impressed with the impromptu plug-in and jQuery!
Two of the things I did differently to get this to work was to add the two
return false;
statements under the state0 block and...
to set the the ajax call to
async: false,
Here's the new javascript:
$('#linkTestPost').click(function() {
TestPost();
});
function TestPost() {
var temp = {
state0: {
html: 'Are you sure you want to post?<br />',
buttons: { Yes: true, No: false },
focus: 1,
submit: function(v, m, f) {
if (v) {
if (PostView() === true) {
$.prompt.goToState('state1');
// the line below was missing from my original attempt
return false;
}
else {
$.prompt.goToState('state2');
// the line below was missing from my original attempt
return false;
}
}
else {
return false;
}
}
},
state1: {
html: 'Test Post was successful!',
buttons: { Close: 0 },
focus: 0,
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
},
state2: {
html: 'Test Post was not successful',
buttons: { Close: 0 },
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
}
};
$.prompt(temp);
}
function PostView() {
var form = $('frmTestPost');
var postSuccess = new Boolean();
$.ajax(
{
type: 'POST',
url: '/Path/TestPost',
data: form.serialize(),
// the line below was missing from my original attempt
async: false,
success: function(data) {
postSuccess = true;
},
error: function() {
postSuccess = false;
}
});
return postSuccess;
}

Resources