2017-06-23 14 views
3

ASP.Netで作業しているとき、私はしばしば "本当ですか?"削除ボタンのようなものをクリックすると、ポップアップが表示されます。これは簡単そうのように行われます。SweetAlert2を使用してASP.Netボタンの "return confirm()"を置き換えます。

<asp:Button runat="server" id="btnDelete" Text="Delete" onClientClick="return confirm('Are you sure?');" onClick="btnDelete_Click" /> 

私は本当にSweetAlert2の確認ダイアログのスタイリングと一般的な感じのような、しかし、彼らは一見よもう少し面倒私は同様の方法でそれらを統合しようとしていたとき。 SweetAlert2ダイアログの結果を、クリックしたボタンに基づいて続行するか停止するかを、どのようにして返すことができるかを誰かに説明することはできますか?

<asp:Button runat="server" id="btnDelete" Text="Delete" onClientClick="return sweetAlertConfirm();" onClick="btnDelete_Click" /> 
function sweetAlertConfirm() { 
     event.preventDefault(); 
     swal({ 
      title: 'Are you sure?', 
      text: "You won't be able to revert this!", 
      type: 'warning', 
      showCancelButton: true, 
      confirmButtonColor: '#3085d6', 
      cancelButtonColor: '#d33', 
      confirmButtonText: 'Yes, delete it!' 
//  }).then(function() { 
//   CONFIRM WAS CHOSEN 
//  }, {function() { 
//   CANCEL WAS CHOSEN 
     }); 
    } 

ダイアログが起動し、私は現在event.preventDefault()をやっているよう削除は、当然のことながら、処理されず、何もありません:ここでは

は、私がこれまで持っているものです返されます。私も I can use promisesに気づいていて、私の swal({...})の後に .then()を追加しましたが、このインスタンスでどのように使用されるか分かりません。

コードビハインドメソッドを実際にトリガーする隠しボタンを使用する必要がある場合は、ユーザーの選択に基づいてその非表示ボタンをクリックすることができますが、これを避けることを望んでいます。

答えて

3

SweetAlert2ダイアログは非同期に処理されるため、約束が解決されたときに別のボタンクリックをプログラムでクリックする必要があります。隠しボタンを作成する代わりに、アクションがすでに確認されたことを示すフラグを設定してbtnDeleteを再利用することができます。このフラグは、2回目のクリックが処理されたときに検出され、ボタンのクリックは続行され、サーバーイベントがトリガーされます。私が探しているもののため

<asp:Button ... OnClientClick="return sweetAlertConfirm(this);" OnClick="btnDelete_Click" /> 
function sweetAlertConfirm(btnDelete) { 
    if (btnDelete.dataset.confirmed) { 
     // The action was already confirmed by the user, proceed with server event 
     btnDelete.dataset.confirmed = false; 
     return true; 
    } else { 
     // Ask the user to confirm/cancel the action 
     event.preventDefault(); 
     swal({ 
      title: 'Are you sure?', 
      text: "You won't be able to revert this!", 
      type: 'warning', 
      showCancelButton: true, 
      confirmButtonColor: '#3085d6', 
      cancelButtonColor: '#d33', 
      confirmButtonText: 'Yes, delete it!' 
     }) 
     .then(function() { 
      // Set data-confirmed attribute to indicate that the action was confirmed 
      btnDelete.dataset.confirmed = true; 
      // Trigger button click programmatically 
      btnDelete.click(); 
     }).catch(function (reason) { 
      // The action was canceled by the user 
     }); 
    } 
} 
+0

パーフェクト。私はそれを少しでもグローバルに再利用できるように変更するかもしれませんが、あまりにも悪くはありません。私は心からあなたの助けに感謝します! – Santi

+1

以前は忘れてしまったように、あなたの解決策はすでに完全に再利用可能であったと言えます。私はちょうど世界的にやさしいようにいくつかのアイテムの名前を変更したところ、魅力的に機能しました。再度、感謝します。 – Santi

関連する問題