Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Ajax Post executing OnComplete Even If Confirm Fails

I have an Ajax form that lets me dynamically remove rows from a table using the OnComplete AjaxOption. That works great.

The problem is that even if I hit "Cancel" on the confirm dialog, it still executes the OnComplete javascript. So the form doesn't post, but it looks like it did to the user (the row is removed from the table).

Any ideas? Source code below:

OnComplete JS:

 function fadeDel(id) {
    $("#product" + id).fadeOut(500);
  }

Form Code:

<% using (Ajax.BeginForm("DeleteProduct", "Commerce", new { id = product.Id }, 
    new AjaxOptions 
    { 
      OnSuccess = "fadeDel(" + product.Id + ")", 
      Confirm = "Are you sure you want to delete" + product.Title 
    }, new { id = "frm" + product.Id }))
  { %>
    <%= Html.SubmitImage("Delete", Url.Content("~/content/images/12-em-cross.png"))%>
<%} %>
like image 728
jchapa Avatar asked Jan 14 '10 20:01

jchapa


1 Answers

The OnSuccess parameter takes a string which gives the name of a function to be called, not the actual function call. So you can pass it "fadeDel", but not "fadeDel(5)". When you do pass it a Javascript call, it's evaluating it immediately, so it's executing fadeDel(5) right when you click submit, even before the AJAX call is made. You can verify that by debugging with Firebug or IE tester tools.

If you want to handle this with an OnSuccess method, it'll need to be one that doesn't take any parameters. One way to do that is by grabbing the product ID from "this", which will be the submitting form. You could either parse it from the Form ID, or just include it in the form's Title or Name property:

<% using (Ajax.BeginForm("DeleteProduct", "Commerce", new { id = product.Id }, 
new AjaxOptions 
{ 
  OnSuccess = "fadeDel", 
  Confirm = "Are you sure you want to delete" + product.Title 
}, new { id = "frm" + product.Id, name = product.Id }))
{ %>
  <input type="submit" name="Delete" />
<%} %>

Then you can update fadeDel to pull the value from 'this':

function fadeDel() {
    var id = this.name;
    $("#product" + id).fadeOut(500);
}

There are other ways to handle this - e.g. a jQuery.ajax() call - but a parameterless OnSuccess call should work fine.

like image 162
Jon Galloway Avatar answered Nov 05 '22 05:11

Jon Galloway