2017-04-11 50 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