0

I have a form that has been created using Ajax.BeginForm. The form submits filtering requirements and displays the results using ajax.

I now want to add an "export" button or a link that will submit that form using a full postback because the action then changes the response headers to change the content type to Excel. The problem is that the unobtrusive javascript uses ajax to render the html.

Here is the script I have used to submit the form from an "Export" link:

$("#export").click(function () {
    var $form = $(this).closest("form");
    $form.append($("<input type='hidden' name='export' value='true' />"));
    $form.trigger("submit");
    return false;
});

I have seen this question Ajax.BeginForm force full postback but I am not keen on altering the unobtrusive script

EDIT I found this technique for forcing the postback:

$("#export").click(function () {
    var $form = $(this).closest("form");
    $form.append($("<input type='hidden' name='export' value='true' />"));
    //$form.data("ajax", ""); //didn't work
    $form.attr("data-ajax", "");//but this did
    $form.trigger("submit");
    return false;
});

What happens now is that the excel file downloads, but the original html page is left with ajax disabled...

Community
  • 1
  • 1
Colin
  • 22,328
  • 17
  • 103
  • 197
  • 1
    http://stackoverflow.com/a/16670517/1182982 – Yasser Shaikh Apr 03 '14 at 10:55
  • @Yasser. Nice idea but I am trying to avoid having to re-engineer the Ajax.BeginForm to jQuery's ajax. If I was using a script to submit I could avoid the call to the script in the first place. – Colin Apr 03 '14 at 11:01

1 Answers1

1

I found that this worked

$("#export").click(function (evt) {
    evt.preventDefault();
    var $form = $(this).closest("form");
    var tempInput = $("<input type='hidden' name='operation' value='export' />");
    $form.append(tempInput);
    $form.attr("data-ajax", "");
    $form.trigger("submit");
    //setTimeout(function () {//thought I might need a timeout to delay the 
                             //reset to after submit but it appears to work 
                             //without
        $form.attr("data-ajax", "true");
        tempInput.remove();
    //}, 0);
});
Colin
  • 22,328
  • 17
  • 103
  • 197