简体   繁体   中英

How do I redirect from one Async Action to Another (MVC5)

I have an Admin section to my site, where I want admin people to be able to add new users. I also have a separate Register Link, which works.

I want to use ajax to update my admin section. So the plan is:

  1. Admin fills in form of user info
  2. AdminController checks if it is valid and then redirects to the AuthenticationController method to create the user
  3. If the AuthController returns success, then reload the list of all users
  4. return this to the partial to update the screen.

When I debug the code, I hit the Admin controller, but I cannot step into the AuthController to see why it is failing. (It all compiles OK)

I assume it is something to do with the fact that my two methods are both async, but I cannot await the redirect from one to the other.

Briefly, the code is;

[Authorize(Roles = "AccessAllAreas")]
[HttpPost]
[ValidateAntiForgeryToken()]        
public async Task<PartialViewResult> CreateNewUser(ApplicationUserViewModel avm)
{
    if (ModelState.IsValid)
    {
        try
        {
            var foo = RedirectToAction("RegisterAsyncFromOtherController", "Account", avm);

    ....
    }

[Authorize(Roles = "AccessAllAreas")]
[ValidateAntiForgeryToken()]
public async Task<ActionResult> RegisterAsyncFromOtherController(ApplicationUserViewModel model)
{
    if (ModelState.IsValid)
    {
        ....
    }
}

A break point on the above if (Modelstate.IsValid) is never hit. However a breakpoint and then step into on the call to RegisterAsyncFromOtherController() accesses one of the properties on the view model, then it returns to CreateNewUser . (Which is what makes me suspect that the async is not working correctly).

Is there anything wrong with the concept I have here, and what is causing the debug behaviour I am seeing?

a RedirectToAction should be returned to the response so the browser of the visitor can redirect to the given url. Only after that has happened will you hit the RegisterAsyncFromOtherController action.

It seems that you're confusing RedirectToAction() with Response.Redirect() .

RedirectToAction() returns a RedirectToRouteResult (which inherits from ActionResult ), and you have to return it to the caller in order for it to have any effect. If you don't return it, RedirectToAction() won't do anything?

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