1

I'm relatively new to MVC but suppose I have a @Html.ActionLink(.... on my page that links to an Action that generates a file and returns it using:

return File(memoryStream, "application/vnd.ms-excel");

This all works well until there's some kind of issue - either something's gone wrong or there's no file to return.

Returning null makes the webpage go to a blank page. So my question is... How can I gracefully handle this scenario? - ideally displaying some error to the user that something went wrong or there's no file/data available or if this isn't possible, then just ensuring the page doesn't go to a blank page, and just remains as it is.

I suppose I could redirect to the index action but this will refresh the page - are there any alternatives.

Percy
  • 2,855
  • 2
  • 33
  • 56
  • I assume you are working with a file result....you need to add a condition just like in this answer: http://stackoverflow.com/questions/11434345/redirecting-to-mvc-actionresult-from-fileresult – Hackerman May 19 '16 at 16:10
  • Can you render the actionlink only if the file exists? `File.Exists(pathToFile)` – Nick May 19 '16 at 16:11
  • @NicholasV. unfortunately no as the file is generated from the database, I would have do do all the "file processing" on the page load. – Percy May 19 '16 at 16:28
  • @Hackerman - exactly the same situation but the answer is what I'm trying to avoid - reloading the page or another page. – Percy May 19 '16 at 16:29

1 Answers1

1

I would do one of two things:

  1. Return a 404 Not Found response:

    return HttpNotFound();
    
  2. Render a "friendly" error page:

    try
    {
        if (File.Exists(...))
        {
            // Download file
        }
        else
        {
            return View("FileNotFound");
        }
    }
    catch (Exception ex)
    {
        return View("FileError", ex);
    }
    
Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92