IAmGroot
IAmGroot

Reputation: 13865

ASP.NET MVC3: Confirmation Box before submitting

I have the following code which basically is a checkbox that causes a submit to take place. As the task gets deleted for the DB, it is a requirement that some box comes up and says, "are you sure" or the likes, to confirm deletion.

<input type="checkbox" 
       onclick="location.href='@Url.Action("Complete", "Tasks", 
                                           new { TaskID = item.TaskID })'" />

This uses Razor syntax.

Upvotes: 4

Views: 17195

Answers (4)

topsail
topsail

Reputation: 3130

hemant's solution didn't work for me. Moumit's solution did work but not when I moved the confirmation function to a named function in my page's javascript file - the confirmation button displayed but it was not prevented when I hit cancel (and as I write this, I wonder if I only needed to pass an event arg, call e.PreventDefault(), then return true).

Anyhow, here is yet another example, with a little help from JQuery, that did work in my aspnetcore mvc razor page:

$(function () {
    $('#mySaveButton').click(function (e) {
        e.preventDefault();
        if (confirm('Are you sure?')) {
            $('#myForm').submit();
        }
    });
});

I adapted this from a more complete example that is worked out from start to finish with an example project: how to show a confirmation dialog with jquery

Upvotes: 0

Moumit
Moumit

Reputation: 9630

It can be done this way

<input name="button"  type="submit" value="Delete" class="btn btn-danger cancel" onclick="return confirm('Are you sure?')" />

Upvotes: 4

hemant
hemant

Reputation: 2445

You may intercept the form submit event and ask confirmation. based on that return true or false to allow submit. akin

 $("#form").submit(function (event) {


   if ( confirm("Are you sure you want to delete"))
       return true;
 else{
     event.preventDefault();
     return false;
      }
   });

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

You could use the confirm method:

<input type="checkbox" onclick="if (confirm('Are you sure?')) { window.location.href = '@Url.Action("Complete", "Tasks", new { TaskID = item.TaskID })'; }" />

or in a more unobtrusive way with jquery:

<input type="checkbox" id="complete" name="complete" data-url="@Url.Action("Complete", "Tasks", new { TaskID = item.TaskID })" />

and then in a separate javascript file:

$(function() {
    $('#complete').click(function() {
        if (confirm('Are you sure?')) {
            window.location.href = $(this).data('url');
        }
    });
});

Also I would very strongly recommend you using another verb than GET on controller actions that modify state on your server such as marking a task as completed. PUT, POST and DELETE are good candidates. In your case since you are modifying an existing item the POST verb seems most natural.

Upvotes: 12

Related Questions