简体   繁体   中英

Html.RenderAction fails in page after RedirectToAction()

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM