0

Using MVC2 I have created a form using the Ajax helper in a view. The form posts to a controller which binds to a model object. A PartialViewResult is returned by the controller and the HTML gets updated into a div. So far, so good.

I now need to submit the same form and return the results in a generated file for the user to download. Obviously I don't want the file contents going into my div.

Is there an elegant way to handle this situation without having to hack it to bits? I'm fairly new to MVC / AJAX and it's still a point of confusion for me.

Chris Johnson
  • 1,374
  • 1
  • 11
  • 10

2 Answers2

1

You may not use ajax call to download files. Following links may help you to do what you are trying to do JQuery Ajax call for PDF file download
http://forums.asp.net/t/1683990.aspx/1

Community
  • 1
  • 1
Tassadaque
  • 8,129
  • 13
  • 57
  • 89
1

OK, so I couldn't find any simple solutions anywhere so I came up with my own. I remove the Ajax event handlers from the form when I want the download, put them back when I want the Ajax. I'm guessing there's a more elegant way to do this, as this feels like a 'clever trick'. I'm open to better suggestions but so far this is my preferred method.

Reference ToggleAjax.js on my page:

var ToggleAjax = function ($, form) {
    var onclick = form.onclick,
        onsubmit = form.onsubmit;

    $('input[class*="ajax-enabled"]').click(function () {
        form.onclick = onclick;
        form.onsubmit = onsubmit;
    });
    $('input[class*="ajax-disabled"]').click(function () {
        form.onclick = function () { };
        form.onsubmit = function () { };
    });
};

Then I call ToggleAjax on my page and pass in the form:

$(function () {
    ToggleAjax($, $('form')[0]);
});

And of course I add the class ajax-enabled or ajax-disabled to the input controls.

Chris Johnson
  • 1,374
  • 1
  • 11
  • 10