2017-04-11 52 views
0

我有這樣的控制器:如何將文件傳遞給控制器​​

public ActionResult Index(HttpPostedFileBase file) 
    { 
     if (file != null && file.ContentLength > 0) 
      try 
      { 
       string path = Path.Combine(Server.MapPath("~/Files"), 
              Path.GetFileName(file.FileName)); 
       file.SaveAs(path); 
       ViewBag.Message = "Success"; 
      } 
      catch (Exception ex) 
      { 
       ViewBag.Message = "Error:" + ex.Message.ToString(); 
      } 

     return RedirectToAction("NewController", new { myFile : file }); 
    } 

我的新控制器:

public ActionResult NewController(HttpPostedFile myFile) 
{ 

} 

我想「文件」傳遞給NewController但它給了我一個錯誤在RedirectToAction。我如何將正確的值傳遞給RedirectToAction以便它能正常工作?謝謝。

+0

什麼是錯誤 –

回答

2

該文件可能是非常複雜的對象,您無法在簡單的RedirectToAction中傳遞潛在的複雜對象。因此,您必須將File存儲在Session中,以便在下一次重定向時獲得它,但由於性能上的考慮,將數據存儲在Session中並不好,並且您必須在從中檢索數據後將Session設置爲空。 但是,您可以使用TempData而不是在後續請求期間保持活動狀態,並且在您從其檢索數據後立即銷燬它。

所以只需將您的文件添加到TempData中,並在新控制器操作中檢索它。

另一件我注意到,你正在Message存儲在ViewBag。但ViewBag在重定向期間變爲空,因此您的NewControllerAction操作中將無法獲得ViewBag.Message。要使其在NewControllerAction中可訪問,您必須將其存儲在TempData中,但Message將具有簡單的string,因此您可以將其作爲參數傳遞給NewControllerAction操作。

public ActionResult Index(HttpPostedFileBase file) 
{ 
    string Message = string.Empty; 
    if (file != null && file.ContentLength > 0) 
    try 
     { 
      string path = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName)); 
      file.SaveAs(path); 
      Message = "Success"; 
     } 
     catch (Exception ex) 
     { 
      Message = "Error:" + ex.Message.ToString(); 
     } 

     //Adding File in TempData. 
     TempData["FileData"] = file; 
     return RedirectToAction("NewControllerAction", "NewController", new { strMessage = Message }); 
} 

在新的控制器:

public ActionResult NewControllerAction(string strMessage) 
{ 
    if(!string.IsNullOrWhiteSpace(strMessage) && strMessage.Equals("Success")) 
    { 
     HttpPostedFileBase myFile = TempData["FileData"] as HttpPostedFileBase; 
    } 
    else 
    { 
     //Something went wrong. 
    } 
} 
+0

似乎預期並不容易 - 你確定它不會觸發'InvalidCastException'這樣的情況:HTTP://計算器。 COM /問題/ 849200 /怎麼辦,我鑄 - 從系統的Web-httppostedfilebase到系統網絡httppostedfile? –

+0

謝謝指出。我用'as'關鍵字。它拋出對象而不拋出任何異常。 – mmushtaq