4

In MVC, is there a way to return a FileStreamResult if my query is successful, but if not, just return the View with an error in the ViewBag. Like so....

    public FileStreamResult Submit()
    {
        string retVal;
        try
        {
            DataSet ds = new DataSet();

            ds = getDS();
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                ExcelXmlWorkbook book = ExcelXmlWorkbook.DataSetToWorkbook(ds);
                string fileName = "results.xml";
                book.Export(fileName, ExportFormat.Xml, 0);
                FileInfo info = new FileInfo(fileName);
                return File(info.OpenRead(), "application/x-msexcel");
            }
            else
            {
                retVal = "No Data";
            }

        }
        catch (Exception ex)
        {
            retVal = ex.Message;
        }

        ViewBag.Result = retVal;

        return View("ViewName");
    }

I know this does not work, but basically, I want to open a results file if the data pull was successful... if it wasn't, I want to display the page, or redirect to a different page to show the user that the results failed. Any suggestions on a better way is also welcomed. Thanks!

Zach
  • 640
  • 1
  • 6
  • 16

1 Answers1

5

Both ViewResult (which is the type returned by the View method) and FileStreamResult derive from the ActionResult class, which represents the result of an action method, so you have to return its instance from Submit.

public ActionResult Submit()
Kapol
  • 6,383
  • 3
  • 21
  • 46
  • @Dom Thanks for noticing. I've edited my post. Actually I made a mistake, because I wrote that `View` derives from `ActionResult`, but `View` is a method, of course :-) – Kapol Jun 20 '16 at 20:17
  • 1
    Thanks for the quick reply! This is exactly what I was looking for. I was a victim of "the answer is so simple it's not"... Thanks again! – Zach Jun 20 '16 at 20:23