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?
RedirectResult is an ActionResult that returns a Found (302), Moved Permanently (301), Temporary Redirect (307), or Permanent Redirect (308) response with a Location header to the supplied URL. It will redirect us to the provided URL, it doesn't matter if the URL is relative or absolute.
You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is: return RedirectToAction("Index", model); Then in your Index method, return the view you want.
Use RedirectToActionResult in ASP.NET Core MVC This action result can be used to redirect to the specified action and controller. If no controller is specified it redirects to the specified action within the current controller.
RedirectToAction will return a http 302 response to the browser and then browser will make GET request to specified action. Show activity on this post. Ideally I would use RedirectToRoute for Action Links/Images and RedirectToAction in Controller's Action to redirect to another Controller's Action .
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"
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With