0
votes

I want to be able to receive open/save dialog for a pdf file being returned from controller without using 'Html.Beginform' in ASP.NET MVC. I´m using 'Ajax.Beginform' since I can register events to fire OnBegin and OnComplete (which I think I can´t do when using Html.Beginform, or is it?).

I want to state that the problem is not creating and receiving the file from the server when using 'Html.Beginform' because that works fine, but without the events I want to use. I´m using 'Ajax.Beginform' and the file is being returned from the controller but nothing happens after that client side.

My cshtml

@using (Ajax.BeginForm("CreatePdf", "Print", null, new AjaxOptions() { LoadingElementId = "printLoading", OnSuccess = "printPageComplete"}, new { id = "exportForm" }))
{
    //Stuff abbreviated
    <input type="button" onclick="onPrint()" />
}

My jQuery

function onPrint()
{
    //Stuff abbreviated
    $("#exportForm").submit();
}

function printPageComplete(result)
{
    //this 'result' variable is obviously holding the file from the controller

    //stuff abbreviated

    //TODO: I need to open file dialog here
}

My Controller

[HttpPost]
public ActionResult CreatePdf(FormCollection collection)
{
    //Stuff abbreviated
    return File(thePdf, _mimeTypes[ExportFormat.Pdf], "thePdf.pdf")
}

As you can see I´ve managed to get this far as in the printPageComplete function but I´m not sure where to go from here. Should I continue using the ajax form or should I stick with the html form and try to find other way to fire the events I so sorely need to use?

Perhaps I´m going about this all wrong and your help would be very well appreciated.

1

1 Answers

0
votes

You can post a form without using Ajax.BeginForm. It is more work, but gives you more flexibility:

$('#exportForm').submit(function (e){
   e.preventDefault();

  //Do any validation or anything custom

  $.ajax({
     //set ajax settings

     success: function(){
       // Handle the success event
     }
    });
});