Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

c# - Redirecting to MVC ActionResult from FileResult

This might be a simple one but here goes:

I'm implementing an excel downloadable report in my MVC3 application. I've used this method in the past and it's worked perfectly, however in this case, there is a chance that sales data may not exist for the report. Here is my code:

I have a FileResult action within a Reports controller:

    [HttpPost]
    public FileResult ExcelReportDownload(ReportExcelDownloadRequest reportRequest)
    {
        ReportEngine re = new ReportEngine();

        Stream report = re.GetReport(reportRequest);

        return new FileStreamResult(report, "application/ms-excel")
        {
            FileDownloadName = "SalesReport.xls"
        };
    }

My issue is that sometimes the report stream may be null meaning that there's no sales info available, in which case I would rather redirect to a View that displays a message to say there is no sales information available, however I am not sure how to achieve this.

Is there a way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, FileResult inherits from ActionResult :

If you result can be either a RedirectToRouteResult (inheriting from ActionResult) or a FileResult, then... your action must be of type ActionResult, which can manage both.

something like that :

    [HttpPost]
    public ActionResult ExcelReportDownload(ReportExcelDownloadRequest reportRequest)
    {
        ReportEngine re = new ReportEngine();

        Stream report = re.GetReport(reportRequest);
        if (report == null)
           return RedirectToAction(<action Name>);
        else
           return new FileStreamResult(report, "application/ms-excel")
           {
               FileDownloadName = "SalesReport.xls"
           };
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...