I have the following Controller Action:
public ActionResult MyAction(...)
{
ActionResult result = View("MyView", new MyModel());
var fruit = TempData["Fruit"];
// Do something with the fruit
return result;
}
and this MyView.cshtml
@model MyModel
@{
TempData["Fruit"] = "Mango";
}
When I put a breakpoint in the View where TempData["Fruit"] is set, it isn’t called before the “return result” in the Action. The Razor rendering seems to be delayed.
How can I force the View to be rendered on return from the result = View(..) call?
Note: Don’t worry about this simplistic example. We have a real use case where a solution to this would really be needed but I didn’t want to burden the question any further.
The View isn’t rendered until after the Action is complete. You can call result.ExecuteResult(ControllerContext) to force the early execution of the ActionResult inside the action like this:
But you will then have a problem because the ActionResult will be executed again when the action returns the result, so you will have to cancel that second execution.
You can do this like so:
This all does seem like a bit of a hack, but in some scenarios it seems necessary. For instance if a child action needs to tell the top level action to carry out a redirect, we won’t know the redirect is required until the child action completes, but the child action won’t be completed until too late. This is the only workaround I’ve been able to find.