jason
jason

Reputation: 7164

How to pass a file to a controller

I have this controller :

   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 });
    }

My new controller :

public ActionResult NewController(HttpPostedFile myFile)
{

}

I want to pass "file" to the NewController but it gives me an error at RedirectToAction. How can I pass correct values to RedirectToAction so that it will work? Thanks.

Upvotes: 0

Views: 2917

Answers (1)

mmushtaq
mmushtaq

Reputation: 3520

The File is potentially very complex object and you can't pass potentially complex object in simple RedirectToAction. So you have to store File in Session to get it in your next redirection but storing data in Session is not good due to performance perspective and you have to set Session null after retrieving of data from it. But you can use TempData instead which remains alive during subsequent requests and it immediately destroyed after you retrieved data from it.

So just add your file in TempData and retrieve it in New Controller Action.

Another thing that i noticed that you are storing Message in ViewBag. But ViewBag becomes null during redirection, so you won't be able to get ViewBag.Message in your NewControllerAction action. To make it accessible in your NewControllerAction, you have to store it in TempData but Message is going to have simple string so you can pass it as parameter to NewControllerAction action.

 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 });
 }

In your new controller:

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

Upvotes: 2

Related Questions