I was facing a problem when I try to return an Action from another Action. I got something like this:
public ActionResult Action (int param1, string param2)
{
ActionViewModel vm = new ActionViewModel();
vm.Param1Prop = param1;
vm.Param2Prop = param2;
return View(vm);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Action (ActionViewModel vm)
{
//Do Something...
if (vm.DoItAgain)
{
return Action(vm.Param1Prop-1, vm.Param2Prop);
}
return View(vm);
}
When the line return Action(vm.Param1Prop-1, vm.ParamProp); goes to Action(int param1, string param2), executes and everything looks like go well. But don't. The render result looks like return View(vm) was executed instead, all the values of the vm are the same as sended in the Post Action, not the ones i'm passing on return Action(vm.Param1Prop-1, vm.ParamProp);.
I'm not sure why isn't working, the ActionResult returning is being ignored? The code inside the first Action method executes fine (I debug and put a log inside to check it) and the return of the first method is the end of the response so why it looks like that line never happened?
I also try to modify the vm on the PostAction to see if the vm was being infered somehow. That don't work either.
To make that work, I put a RedirectToAction instead of using the return Action:
RedirectToAction("Action", new { param1 = vm.Param1Prop-1, param2 = vm.Param2Prop }); and everything work fine. I completly understand why RedirectToAction works, but i cannot figure out why invoke the Action method don't.
Anyone can enlighten me about it?
What you are probably seeing is the ModelState values from the original POST. These will take precedence over the ones you return to your view. You can rectify this by clearing the values from ModelState. However, you shouldn't need to.
You shouldn't return one action from another. You should return a redirect to that action:
return RedirectToAction("Action",
new { param1 = vm.Param1Prop-1, param2 = vm.Param2Prop });
Because you've performed a proper redirect now instead of just returning the result of the GET action directly from the POST, ModelState will have been cleared when the original request ended and you won't see your old posted values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With