1

I have a page "ViewUser". with this structure

//display something about the user
@{Html.RenderAction("UpdateUser", new { UserId = @Model.UserId });}
//display some more stuff

In the controller method for UpdateUser I have

public ActionResult UpdateUser(int UserId){//populate form vars
[HttpPost]
public ActionResult UpdateUser(User u)//
// code to update the user
return RedirectToAction("ViewUser", new { User = u.UserId });

When I open the page it works fine I see my user data and the date in the UpdateUser form. However when I update the user data and redirect to the ViewUser page from UpdateUser I get "Child actions are not allowed to perform redirect actions."

but opening the page manually again show that the update was successful. As far as I understand the browser should be performing a new GET for everything so I don't understand why it works for a manual refresh but not when UpdateUser returns the redirect?

1 Answers1

3

The error is quite clear:

Child actions are not allowed to perform redirect actions.

When you call an action directly (not as a child action) it's responsibel for deciding what it returns to the browser. So it can decide to return a Redirect.

However, if this action is invoked as a child action, there is already a main Action which has decided what to return to the browser, and is asking this child action to render additional HTML. So, if the child action returns something different, as a Redirect, it fails.

See this, ChildActionExtensions.RenderAction Method:

Invokes a child action method and renders the result inline in the parent view.

A redirect, or anything that is not HTML (a View / PartialView result) can't be rendered inside the parent view.

You could simulate a "redirect" from a child action including an script that redirects the page, by including this JavaScript on it (How can I make a redirect page in jQuery/JavaScript?):

window.location.replace('@Url.Action(...)');

Anyway you'd rather do it from the main view, by using the same logic that you're using on the partial to decide to make the redirect.

Community
  • 1
  • 1
JotaBe
  • 38,030
  • 8
  • 98
  • 117
  • Thanks JotaBe. So how can I return the ViewUser as a non-Child action? Is there anything wrong with this pattern it seems very natural to me? – MrDaultonAtLarge Jan 21 '14 at 11:18