I am working on a single-page application using ASP.Net Core MVC and JQuery (doing a full-page refresh resets some long-running processes, so I must use AJAX for all navigation to avoid this.)
I want to allow the user to download a PDF, which can be handled simply enough using my PdfController:
public async Task<IActionResult> GetFile(int FileID)
{
byte[] fileBytes = await _myService.GetFile(FileID);
return File(fileBytes, "DesiredMimeType", "DesiredFileName");
}
In this simple case, I can use something like <a href="/Pdf/GetFile?FileID=123">Get File 123</a>
and the file downloads without screwing anything up. The problem is that sometimes my service throws an exception if the parameters are incorrect. I would like to be able to display a custom error page (using AJAX), so now my controller action becomes:
public async Task<IActionResult> Index(int FileID)
{
try
{
byte[] fileBytes = await _myService.GetFile(FileID);
return File(fileBytes, "DesiredMimeType", "DesiredFileName");
}
catch (MyCustomException ex)
{
return PartialView("MyErrorPage", new MyErrorViewModel(ex));
}
}
This works fine on the server side, but I don't know how to handle it on the client side. The JavaScript would need to look something like this:
function getFile(fileID) {
$.get('/Pdf/GetFile?FileID=' + fileID, function (data) {
// pseudo code - not sure what to do here
if (isFile(data)) {
// then prompt a download and leave the DOM alone
} else {
// display error page
$('#ajax-container').html(data);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
notify('Web service responded with ' + textStatus);
});
}
So my question is: how can I use JQuery or JavaScript to detect whether data
is a file or a partial view, and how can I trigger a file download if it is a file? If there is a better approach, I am open to recommendations also.