Randy Minder
Randy Minder

Reputation: 48402

MVC - Unable to pass parameter with RedirectToAction

Here is a method (abbreviated) that looks as follows:

        [HttpPost]
        public ActionResult SearchForCompanies(FormCollection collection)
        {
            CompanySearch search = new CompanySearch();

            search.CompanyList = CompanyData.GetList();

            return this.RedirectToAction("SearchForCompanies", "Company", new {companySearch = search});
        }

The method above is redirecting to the method below in the same controller:

    [HttpGet]
    public ActionResult SearchForCompanies(CompanySearch companySearch)
    {
        if (companySearch == null)
            companySearch = new CompanySearch();

        ...
        ...

        return View(companySearch);
    }

On the redirect, the HTTPGet version of SearchForCompanies is getting called successfully. However, the value of the companySearch parameter is always NULL, even though it has a value when the redirect call is made. So I must not be passing the parameter correctly.

Upvotes: 0

Views: 522

Answers (1)

user3559349
user3559349

Reputation:

In order to pass a complex object to an action method, you can use

CompanySearch search = new CompanySearch();
return RedirectToAction("SearchForCompanies", "Company", search);

which will serialize all the properties of CompanySearch to query string parameters. However this will

  1. create an ugly url
  2. throw an exception is the query string limit is exceeded, and
  3. fail if any of the properties of your model are complex objects or collection which appears to be the case with your property CompanyList (the query string become something like ...&CompanyList=System.Collections.Generic.List<...>&...)

Upvotes: 1

Related Questions