简体   繁体   中英

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.

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.

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;
      }
   });

可以这样做

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM