0

I faced the following error while using the RedirectToAction method in ASP.NET MVC 5.

    [HttpPost]
    public ActionResult UploadOrderReport(HttpPostedFileBase file)
    {
        string targetFolder = HttpContext.Server.MapPath("~/Reports");
        string targetPath = Path.Combine(targetFolder, file.FileName);
        file.SaveAs(targetPath);

        var currentReports = Directory.GetFiles(targetFolder).ToList();
        return RedirectToAction("CurrentProfile", new { existReport = new List<string>(currentFiles)});
    }

However, in my CurrentProfile method I got unexpected data

[HttpGet]
public ActionResult Index(List<string> existReports)

and debugger shows that existsReports argument is System.Collections.Generic.List``1[System.String]

I suppose my problem related to type casting?

Eonasdan
  • 7,563
  • 8
  • 55
  • 82
Iskander Raimbaev
  • 1,322
  • 2
  • 17
  • 35

1 Answers1

2

RedirectToAction method is going to return a 302 response to your browser with the new url as the location header value. The browser will make a new HTTP request to this new url.

If you look at the RedirectToAction method overloads, you can see that the third parameter is for routevalues(which will for the querystring values)

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    object routeValues
)

You should not be passing complex data(like a list of items) to the RedirectToAction method. Basically, when you pass some small objects,it will be converted to the querystring values.

If you want to pass a complex data, i suggest you to pass a uniqueId from which the list can be retrieved in your GET action again. If that is not an option, consider using TempData.

Passing a unique id

return RedirectToAction("CurrentProfile",new { listId="someUniqueIdHere"});

This will set the location header value as /YourController/CurrentProfile?listId=someUniqueIdHere

Passing via TempData

TempData["existReport "] = new List<string>(currentFiles);
return RedirectToAction("CurrentProfile", "yourControllerName");

And read it in your CurrentProfile GET Action method again.

public ActionResult CurrentProfile()
{      
  var items=TempData["existReport"] as List<string>
  return View(model);
}

Take a look at How do I include a model with a RedirectToAction? as well

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497