Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a FileStreamResult if successful or View if unsuccessful

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!

like image 705
Zach Avatar asked Oct 20 '25 04:10

Zach


1 Answers

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()
like image 134
Kapol Avatar answered Oct 21 '25 18:10

Kapol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!