user979331
user979331

Reputation: 11861

ASP.NET RedirectToAction with parameters not getting passed

I am trying to do a RedirectToAction with parameters like so:

return RedirectToAction("Index", "CPLCReservation", new { data = cp_sales_app_lc });

I am trying to pass the data to the CPLCReservation Controller's Index Method.

When I put a break point at the RedirectToAction, I can see cp_sales_app_lc is populated, when I goto the Index method of CPLCReservation Controller:

public ActionResult Index(CP_Sales_App_LC data)
        {
            return View(data);
        }

data is null. Am I passing the data wrong?

cp_sales_app_lc is class variable of CP_Sales_App_LC and its defined like so:

CP_Sales_App_LC cp_sales_app_lc = new CP_Sales_App_LC();

I hope all this makes sense.

Upvotes: 0

Views: 1623

Answers (3)

Marcio Cardoso
Marcio Cardoso

Reputation: 88

If data is simple var type, like string or int, you can call:

return RedirectToAction("Index", "CPLCReservation", new { data = cp_sales_app_lc });

But if your var is complex, like a class with many items, you can use use the

ViewBag.data = cp_sales_app_lc
return RedirectToAction("Index", "CPLCReservation");

and then on CPLCReservation controller you recall the viewmodel

CP_Sales_App_LC data = (CP_Sales_App_LC)ViewModel.data;
return View(data);

to transport the complex model, like @Vadym Klyachyn said.

Also you can direct call the action like

return Index(cp_sales_all_lc);

but take in mind that if you have more code after it, it will return and execute that code. It wont leave the controller that call it.

I think the best way if you don't need a new controller is to use only a new View with the same controller with that model:

return View("newViewToDisplaydata", cp_sales_all_lc)

Upvotes: 0

Vadym Klyachyn
Vadym Klyachyn

Reputation: 106

In this case you can catch parameter as string: `

public ActionResult Index(string data)
{
    return View(data);
}

Or you can do following:

public ActionResult SomeAction()
{
   TempData["data"]= new CP_Sales_App_LC();
   return RedirectToAction("Index", "CPLCReservation");
}

public ActionResult Index()
{
   CP_Sales_App_LC data = (CP_Sales_App_LC)TempData["data"];
   return View(data);
}

Upvotes: 0

Sam Axe
Sam Axe

Reputation: 33738

RedirectToAction is handled via an HTTP status code (302 usually). These redirects, as of HTTP 1.1, are always done via the HTTP verb GET.

Passing your object to the url parameter data will not call any serialization code. (GET only deals with the URL, thus only strings). You would have to serialize your object to use it with RedirectToAction.

Another option is to call the action method directly:

// Assuming both actions are in the CLPCReservationController class
public ActionResult SomeOtherEndpoint() {
    // return RedirectToAction("Index", "CPLCReservation", new { data = cp_sales_app_lc });
    return Index(cp_sales_all_lc);
}

Upvotes: 1

Related Questions