Ajax.BeginForm OnBegin confirmation Via jquery modal

I am using the jQuery UI dialog. I have a removal form as follows:

@using (Ajax.BeginForm("DeleteUser", "Administrator", new { id = Model }, new AjaxOptions { OnSuccess = "Deleted", OnBegin = "DeletingUser" }, new { id = "frm" + Model, name = Model })) { <input type="submit" value="" /> } 

I want modal confirmation to appear before sending the ajax request, and the user selects yes or no.

Here is my javascript:

 <script> function DeletingUser(){ $( "#dialog-confirm" ).dialog({ resizable: false, height:140, modal: true, buttons: { "Delete all items": function() { $( this ).dialog( "close" ); }, Cancel: function() { $( this ).dialog( "close" ); } } }); //I need to return a true or false here depending on the button clicked. } </script> <div id="dialog-confirm" title="Empty the recycle bin?"> <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p> </div> 

As you can see from the javascript code, the dialog opens asynchronously, which leads to the fact that the method returns nothing and the form submitted in any case without the user choosing yes or no. How to fix it?

+4
source share
3 answers

You can use regular Html.BeginForm and AJAXify with jquery. You will have much more control compared to the Ajax.BeginForm :

 @using (Html.BeginForm( "DeleteUser", "Administrator", new { id = Model }, FormMethod.Post, new { id = "frm" + Model, name = Model } )) { <input type="submit" value="" /> } 

and then in a separate javascript file simply:

 $(function() { $('form[id^="frm"]').submit(function() { var $form = $(this); $('#dialog-confirm').dialog({ resizable: false, height:140, modal: true, buttons: { 'Delete all items': function() { $(this).dialog('close'); // the user confirmed => we send an AJAX request to delete $.ajax({ url: $form.attr('action'), type: $form.attr('method'), data: $form.serialize(), success: function(result) { Deleted(result); } }); }, Cancel: function() { $(this).dialog('close'); } } } return false; }); }); 
+6
source

I think the form is submitting because your DeletingUser is not available in the post. time. see stackoverflow article (no solution yet)

0
source

Trick. This is my first post, I spend a lot of time to resolve this issue, I think it is easier:

  dialog: function smOpenConfirmDialog(callBack) { $("#noticeDialog").dialog({ autoOpen: true, modal: true, autoOpen: false, draggable: false, buttons: { "Confirm": function () { callBack(); $(this).dialog("close"); }, "Cancel": function () { $(this).dialog("close"); } } }); 

and

  $("input:submit").click(function (e) { smOpenConfirmDialog(function () { $("form").trigger('submit'); }); e.preventDefault(); }); 
0
source

Source: https://habr.com/ru/post/1346979/


All Articles