Passing info to another action using RedirectToAction - MVC

六眼飞鱼酱① 提交于 2019-11-30 09:43:17

问题


I have this action:

    public ActionResult Report(AdminReportRequest reportRequest, FormCollection formVariables)
    {
        AdminEngine re = new AdminEngine();

        AdminReport report = re.GetCompleteAdminReport(reportRequest);

        return View(report);
    }

I was wondering how could I go about Redirecting to another action within the same controller, passing the AdminReportRequest, and FormCollection variables?

I had something like this in mind:

    public ActionResult EarningsSalesReport(AdminReportRequest reportRequest, FormCollection formVariables)
    {
        if (!reportRequest.Download)
        {
            AdminEngine re = new AdminEngine();

            AdminReport report = re.GetCompleteAdminReport(reportRequest);

            return View(report);
        }

        return RedirectToAction("ExcelSalesReport", reportRequest, formVariables);

    }

    public FileResult ExcelSalesReport(AdminReportRequest reportRequest, FormCollection formVariables)
    {
        AdminEngine re = new AdminEngine();

        Stream SalesReport = re.GetExcelAdminReport(reportRequest);

        return new FileStreamResult(SalesReport, "application/ms-excel")
        {
            FileDownloadName = "SalesReport" + DateTime.Now.ToString("MMMM d, yyy") + ".xls"
        }; 
    }

This is obviously wrong and throws up some errors, such as:

'System.Web.Mvc.Controller.RedirectToAction(string, string, System.Web.Routing.RouteValueDictionary)' has some invalid arguments

and

Argument 3: cannot convert from 'System.Web.Mvc.FormCollection' to 'System.Web.Routing.RouteValueDictionary'

If someone could point me in the right direction I'd greatly appreciate it, I think I might have to edit the Global.asax file however I'm not overly familiar with this.

thanks.


回答1:


You can use the TempData object.

The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out.

This MSDN article explains it all.

public ActionResult EarningsSalesReport(AdminReportRequest reportRequest, FormCollection formVariables)
{
   //...
   TempData["Report"] = reportRequest;  //store to TempData
   //...
}

public FileResult ExcelSalesReport(AdminReportRequest reportRequest, FormCollection formVariables)
{
  //...
  var report = TempData["Report"] as AdminReportRequest;
  //...
}


来源:https://stackoverflow.com/questions/5753720/passing-info-to-another-action-using-redirecttoaction-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!