Ajax.BeginForm force full postback

2019-07-16 05:04发布

问题:

How do I force Ajax.BeginForm (MVC3, unobtrusive) to do a full postback?

In MVC2 I just cleared the "onclick" and "onsubmit" handlers. How do I do this in MVC3?

//does not work in MVC 3 with unobtrusive ajax :((
$('#myForm').unbind('click');
$('#myForm').unbind('submit');

PS. In case you're interested, I need this for file uploads. If no file is being uploaded - ajax is fine. If a file is being uploaded - let it do a full postback.

Update:

After looking at "jquery.unobtrusive-ajax.js" source code I saw this:

$("form[data-ajax=true]").live("submit", blahblah);

So I came up with this and it works:

$("form[data-ajax=true]").die("submit");

But this seem a little "hacky", any "legitimate" way to clear all onsubmit events from a form? I guess the updated question is now: How do I clear a "live" event-handler with a "die" statement that uses a different selector?

回答1:

If you are fine with modifying the unobtrusive library.. you can check in the submit event handler whether the form contains any file and if yes then do a full POST else through AJAX.

$("form[data-ajax=true]").live("submit", function (evt) {
    var clickInfo = $(this).data(data_click) || [];
    evt.preventDefault();
    if (!validate(this)) {
      return;
    }

    if ($("input[type=file]", this).val()) {
      this.submit();
    }
    else {
      asyncRequest(this, {
        url: this.action,
        type: this.method || "GET",
        data: clickInfo.concat($(this).serializeArray())
      });
    }
  });