views:

193

answers:

3

Suppose I have the following actions:

public ActionResult DoSomething()
{
    // Some business logic
    return RedirectToAction("AnotherAction", RouteData.Values);
}

public ActionResult AnotherAction(string name, int age)
{
   ...
}

And the following form:

<form method="post" action="DoSomething">
    <input name="name" type="text" />
    <input name="age" type="text" />
    <input type="submit" value="Go" />
</form>

Hitting submit on that form will go to the DoSomething action, and in turn to AnotherAction - passing in all the relevant values into name and age. It works a treat!

But I obviously cannot access any other submitted form values in AnotherAction, because they are lost when redirecting from DoSomething:

public ActionResult AnotherAction(string name, int age)
{
   // This won't work
   var other = Request.Form["SomeDynamicVariable"];
}

What would be more ideal is a TransferToAction method, that re-runs the MVC engine "imagining" the form had been posted to AnotherAction instead:

return TransferToAction("AnotherAction");

Can I do this?

If this functionality is not available out-of-the-box, then I'll make it, blog it and post it!

+1  A: 

Use the TempData construct to store the Request.Form. TempData is only around for the given request, so it will be cleared after the processing is finished.

public ActionResult DoSomething()
{
    // Some business logic
    TempData["PostedFormValues"] = Request.Form;
    return RedirectToAction("AnotherAction", RouteData.Values);
}

public ActionResult AnotherAction(string name, int age)
{
   ...
   if (TempData["PostedFormValues"] != null)
   {
       //process here
   }
}
womp
It's a nice solution, and would work - but it's not as nice as a TransferToAction that wouldn't require special coding on the receiving method to retrieve the form from TempData
joshcomley
You could quickly write a TransferToAction method in your controller/base controller class. :)
Nathan Taylor
@lakario - I could, but I was wondering if there was already a mechanism to do it in MVC :)
joshcomley
I think the next release of MVC will have some better options available but for now this is the simplest thing to do :(
womp
A: 

One way to do this would be to invoke the second action from the first action and capture the response. This is not trivial, see http://bit.ly/ThtHH

Jan Willem B
A: 

your controller actions are also valid public functions so you can do this

public ActionResult DoSomething(){    
// Some business logic    
// Get Params from Request
      return AnotherAction(name, age);
}

public ActionResult AnotherAction(string name, int age){
   ...
}

when you now access the Request object from AnotherAction it is still the same because you obviously didn't made another request.

marc.d