ASP.NET MVC - Having a confirmation button with a Form

asp.net-mvc-3

Solution

Of course it is possible. I like to use an unobtrusive approach. Here is a simplified example:

jQuery(document).ready(function () {
  jQuery('[data-confirm]').click(function (e) {
    if (!confirm(jQuery(this).attr("data-confirm")))
    {
      e.preventDefault();
    }
  });
});

Then you only need to add a data-confirm attribute to your submit button for example

<input type="submit" data-confirm="are u sure?" />

Of course you can use this attribute on links, buttons, etc. you are not restricted to submit buttons only, and if you want to implement a fancier confirm dialog later than you will have to replace the code only in one place.

Problem

I have an strongly typed view for my model and what I'd like is that when the user clicks on submit, a confirmation box pop up confirming that the user does indeed wish to submit the form, if they click cancel then it shouldn't fire the `HttpPost` Action for that View, is this possible?

Original source