0

Is what I'm trying to do possible? It seems like it should be. I expect to see MyActionMethod go on to the new url, but instead it winds up being called again.

I've simplified this to get down to the essence. My action method is being called from a view with an Ajax.BeginForm(), once submitted, I see it get to here in the controller.

public ActionResult MyActionMethod(MyViewModel myViewModel)
    {
        isRedirectNeeded = true;
        return RedirectIfNeeded(isRedirectNeeded)   
    }

My method to determine where to redirect to. I have a method because it's called a few times and has more destinations than just the one in this example.

  private ActionResult RedirectIfNeeded(bool isRedirectNeeded)
    {
        if (isRedirectNeeded)
        {
            return Redirect(@"~/myController/MyMethod"); 
        }
        else 
        {
            return Json("<div class='alert alert-error'>" + errorMessage + "</div>");
        }
    }

I can step through the debugger, watch it go to MyActionMethod, jump to the redirectIfNeeded method, figure out the correct redirection url to use, and then return. But instead of going to the new url, I just wind up back in MyActionMethod. What's going on here?

I'm not allowed to post actual code.

New Info: I stepped through past the return in MyActionMethod and saw it go to the global.asax and hit this: (It's generic enough that I'm posting actual code)

    protected void Application_EndRequest()
    {
        var context = new HttpContextWrapper(Context);
        if (context.Request.IsAjaxRequest() && context.Response.StatusCode == 302)
        {
            Context.Response.Clear();
            Context.Response.Write("**custom error message**");
            Context.Response.StatusCode = 401;
        }
    }

I'm googling it now, but want to put this info out so you guys are have all the info I do

Answer is in the question referred to in the duplicate comment above.

Brad Boyce
  • 1,248
  • 1
  • 17
  • 34
  • you can't redirect this way when using ajax, you need to return url as json and redirect using javascript – Ehsan Sajjad Mar 13 '15 at 05:06
  • I believe sending http status code and behaving accordingly in javascript is in this case is good practise. http://stackoverflow.com/a/20975397/1505865 – Jenish Rabadiya Mar 13 '15 at 05:10
  • Thanks @Erik Funkenbush, I didn't realize it was an AJAX issue when I first wrote the question. – Brad Boyce Mar 13 '15 at 05:20

1 Answers1

-1

you need to use return RedirectToAction(); to redirect to a different action

Akshay Randive
  • 384
  • 2
  • 10
  • I'm not redirection to a different action. The "RedirectIfNeeded()" is just a private method in the controller that returns an ActionResult. – Brad Boyce Mar 13 '15 at 05:04