#jquery #asp.net #noty
#jquery #asp.net #noty
Вопрос:
У меня есть кнопка ссылки внутри ретранслятора, подобная этой:
<asp:LinkButton ID="lnkDelete" runat="server" CommandName="delete" OnClientClick='javascript:return showConfirm("Are you sure you want to delete?")'
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ReasonId") %>'>Delete</asp:LinkButton>
и я использую плагин jQuery noty, чтобы показывать подтверждение, когда пользователь нажимает на удаление.
showConfirm()
Функция выглядит следующим образом:
function showConfirm(message) {
var n = noty({
text: message, //'Are you sure?',
type: 'confirm',
dismissQueue: false,
layout: 'center',
theme: 'defaultTheme'
, buttons:
[{
addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {
$noty.close(); return true;
}
},
{
addClass: 'btn btn-danger', text: 'Cancel', onClick: function ($noty) {
$noty.close(); return false
}
}]
})
}
Но он не вернет true
или false
. Как я могу вернуть true
или false
при нажатии на ok
cancel
кнопку или.?
Ответ №1:
Аналогично первому ответу, но управление отложенным немного по-другому, что для меня немного более интуитивно понятно.
function showConfirm(msg) {
var self = this;
self.dfd = $.Deferred();
var n = noty({
text: msg,
type: 'confirm',
dismissQueue: false,
layout: 'center',
theme: 'defaultTheme'
, modal: true
, buttons:
[{
addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {
$noty.close();
self.dfd.resolve(true);
}
},
{
addClass: 'btn btn-danger', text: 'Cancel', onClick: function ($noty) {
$noty.close();
self.dfd.resolve(false);
}
}]
})
return self.dfd.promise();
}
Тогда мы можем использовать…
showConfirm("Confirm your action?").then(function (status) {
// status is true or false
});
Ответ №2:
Вы не можете вернуться true
или false
так, как хотите, потому что на самом деле это не «реальный модальный диалог«, который заставляет браузер или любое другое окно ждать возврата.
Единственное диалоговое окно браузера, которое может это сделать, используя javascript, — это confirm
диалоговое окно.
На самом dialog
деле вы используете один div, который открыт на вашей странице и показывает сообщение, неспособное удержать сообщение от вашего элемента управления вводом. В качестве альтернативы вы можете настроить его так, чтобы он открывался, а в случае «Да» перенаправлять на нужную вам страницу, но вызывающая ее ссылка должна открывать только ее.
Ответ №3:
используйте Jquery $.Deferred.
var status = false;
var defer = new $.deferred();
defer.progress(function(status) {
status = status;
if ( status != undefined ) {
defer.resolver();
if ( !status ) {
return false;
} else {
return true;
}
}
});
var confirm = showConfirm("Are you sure you want to delete?", defer);
и.. функция noty
function showConfirm(message, defer) {
var _self = this;
var status = undefined;
var n = noty({
text: message, //'Are you sure?',
type: 'confirm',
dismissQueue: false,
layout: 'center',
theme: 'defaultTheme'
, modal: true
, buttons:
[{
addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {
_self.status = true;
$noty.close();
// return true;
defer.notify(_self.status);
}
},
{
addClass: 'btn btn-danger', text: 'Cancel', onClick: function ($noty) {
$noty.close();
// return false
defer.notify(_self.status);
}
}]
})
}
завершение;
Ответ №4:
Вот пара небольших полезных функций, которые я написал для noty. эта версия предполагает использование библиотеки animate.css и foundation framework, однако она будет работать с bootstrap до тех пор, пока вы заменяете классы css кнопок классами для bootstrap. Имейте в виду, что эта функция предназначена для работы с глобальными функциями пространства имен, поскольку технически они являются просто методами объекта window . если вам нужно использовать функции пользовательского объекта, измените window на имя вашего объекта в строке с надписью «вот где происходит волшебство»
//shows a noty alert message. _m is the message to display, _t is the type(error etc)
function alertHandle(_m,_t){
noty({
text: _m,
type:_t,
layout:'topCenter',
animation: {
open: 'animated pulse',
close: 'animated flipOutX',
}
});
}
//noty confirm dialogue with callback function.
/*
_text = text of message to display
confirmCB = callback function to call if user clicks continue.
args = args to pass to callback function . could be whatever you want it to be.
*/
function confirmModal(_text,confirmCB,args){
noty({
text: _text,
layout: 'center',
buttons: [
{addClass: 'button success tiny radius no-margin', text: 'Continue', onClick: function($noty) {
$noty.close();
window[confirmCB].call(false,args); // heres where the magic happens.
}
},
{addClass: 'button alert tiny radius no-margin', text: 'Cancel', onClick: function($noty) {
$noty.close();
alertHandle('the action was cancelled','information');
}
}
]
});
}
Ответ №5:
function deleteFinance(ItemID, btn) {
noty({
text: 'are you sure of delete Item?', buttons: [{
addClass: 'btn btn-primary', text: 'yes',
onClick: function ($noty) {
$noty.close();
deleteFinance2(ItemID, btn);
}
}, {
addClass: 'btn btn-danger', text: 'Cancel',
onClick: function ($noty) {
$noty.close();
}
}]
, layout: 'center'
});
}