mornaner
mornaner

Reputation: 2424

Downloading a file but returning Ajax response when there is an exception in asp.net-mvc 3

I have the following code in my controller:

public ActionResult downloadFile()
    {
        try
        {
            FileStream fs = new FileStream(helper.getFileLoc(), FileMode.Open);
            string mimeType = "Text File";
            FileStreamResult f = File(fs, mimeType, "myFile.txt");
            return f;
        }
        catch
        {
            return PartialView("_errorFile");
        }
    }

I want to download a file, but if there is an exception I want to render the partial view in my errors div.

The problem is that if I use @Html.ActionLink to call the method I get the file to download right, but if there's an exception I get redirected to a page containing only the partial view.

On the other hand, if I use @Ajax.ActionLink, I get the exception handled correctly in that div, but if there isn't an exception I get the text inside the file instead of a download.

Is there any way to do what I am trying to do here?

Upvotes: 2

Views: 1453

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156624

The best approach I've found so far is to perform the download in two stages: the first one can be called via AJAX, and checks for potential causes of errors. If the first one returns a go-ahead message, the javascript then changes window.location to the "confirmed" download URL.

This approach won't very well handle exceptional cases, like where the network drive gets yanked out of the server between these two requests. But it should gracefully handle the most common issues, like where the user doesn't have rights to download the requested file.

Upvotes: 3

Related Questions