Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 659
IAmGroot Avatar asked Dec 04 '22 06:12

IAmGroot


2 Answers

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.

like image 119
Darin Dimitrov Avatar answered Dec 11 '22 20:12

Darin Dimitrov


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;
      }
   });
like image 35
hemant Avatar answered Dec 11 '22 20:12

hemant