37

I tried using a RedirectToAction after I have done a post to the controller and saved but the URL does not change and the redirect does not seem to work. I need to add that the redirect does enter the controller action method when I debug. It does not change the URL or navigate to the Index view.

public ViewResult Index()
{
    return View("Index", new TrainingViewModel());
}

public ActionResult Edit()
{
    // save the details and return to list
    return RedirectToAction("Index");    
}

What am I doing wrong?

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{resource}.js/{*pathInfo}");
    routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = "" } // Parameter defaults
    );
}

jQuery calls:

this.SynchValuesToReadOnly = function() {
    window.location = $('#siteRoot').attr('href') + 'Sites/';           
};

this.OnSiteEdit = function() {
    // post back to the server and update the assessment details    
    var options = {
        target: '',
        type: 'post',
        url: '/Site/Edit',
        beforeSubmit: othis.validate,
        success: othis.SynchValuesToReadOnly
    };

    $('#uxSiteForm').ajaxSubmit(options);
};
CarenRose
  • 1,266
  • 1
  • 12
  • 24
kurasa
  • 5,205
  • 9
  • 38
  • 53
  • 7
    The code you show is correct. My wild guess is that you're not doing a standard POST (e.g., redirects don't work with an AJAX post). Can you show more code? – Craig Stuntz Feb 08 '10 at 21:37
  • aaaaahhh....did not know that. Yes you are right. It is indeed coming from an ajax post in jquery and that means I should redirect from there if successful. No problems. Put your comment up as an 'answer' and I'll mark when I prove it works if you like thanks – kurasa Feb 08 '10 at 21:41

8 Answers8

95

The code you show is correct. My wild guess is that you're not doing a standard POST (e.g., redirects don't work with an AJAX post).

The browser will ignore a redirect response to an AJAX POST. It's up to you to redirect in script if you need to redirect when an AJAX call returns a redirect response.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • Good answer. Can you explain why for us? – one.beat.consumer Jul 06 '12 at 18:04
  • 3
    When you do an async `POST`, you must manually redirect (in JS) if you get a redirect response. Browsers don't do it automatically. That's all there is to say about this. Browsers assume the script is in charge in this case. – Craig Stuntz Jul 06 '12 at 18:16
  • 3
    just complementing and giving some guidance for n00bs like me. In the ajax.beginform instruction, include something like this new AjaxOptions{ OnSuccess="window.location.href = 'ControllerName/Action'" } and voilá – Ricker Silva Feb 04 '14 at 23:45
  • 1
    @Craig Stuntz Actually Chrome and FF are automatically redirecting pretty well. IE (version 11 in my case) doesn't ... but I think at time of the post none did. – Antoine Meltzheim Apr 06 '14 at 00:48
8

You need to add "return false;" to end of your onclick javascript event. For example:

Razor Code

@using (Html.BeginForm())
{
    @Html.HiddenFor(model => model.ID) 
    @Html.ActionLink("Save", "SaveAction", "MainController", null, new { @class = "saveButton", onclick = "return false;" })
}

JQuery Code

$(document).ready(function () {
        $('.saveButton').click(function () {
            $(this).closest('form')[0].submit();
        });
    });

C#

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveAction(SaveViewModel model)
{
    return RedirectToAction("Index");
}
Idris
  • 301
  • 3
  • 3
  • 5
    For some reason, I always forget that "return" is required. Guess I'm so used to the old Response.Redirect that never required a "return". – Eric K Nov 01 '12 at 19:49
6

Try as below:

return in your action:

return Json(Url.Action("Index", "Home"));

and in your ajax:

window.location.href

Prince Agrawal
  • 3,619
  • 3
  • 26
  • 41
thiago.adriano26
  • 1,491
  • 3
  • 14
  • 19
6

I just came across this issue and nothing was working for me. It turned out the controller I was redirecting to required Authorization - the [Authorize] attribute was preventing any redirection.

[Authorize]//comment this out
public class HomeController : Controller {...}

Down the road or in larger projects this may not be a desired fix, but if you're only looking for a simple redirection or starting out, this may be a solution for you.

Drew Kennedy
  • 4,118
  • 4
  • 24
  • 34
  • Now I understand why I kept getting directed to Login when I attempted a redirect, duh. Thanks!! – Mike Mar 17 '22 at 15:59
4

I decided to write this comment as a new answer because I think it needs more description and may someone can't see it in comments if has my problem. So I Apologize if you think this is not an answer and must be written in the comment section.

In some cases, I used RedirectToAction to send the user to another action if input values are incorrect or insufficient and avoid continuing the current process as below:

if (inputValues == null)
{
  RedirectToAction("index");
}

That keeps not working and continues the current process to take unhandled error. I search and read some articles but I can't find a solution. Calling of RedirectToAction is not from Ajax code and routing is so simple without any parameters even. So why is not working? Finally, I found the simple mistake I did: Forgot to put "return" keyword before RedirectToAction. I changed the code as below:

if (inputValues == null)
{
  return RedirectToAction("index");
}

And that is worked. Hope this help.

QMaster
  • 3,743
  • 3
  • 43
  • 56
3

Check with firebug. Post might be returning a server error.

mtmk
  • 6,176
  • 27
  • 32
2

This is a bit late.... but I had the same problem in MVC5. I had 2 actions with the same name, which is common enough. I wasn't getting any errors that I could capture in Application_Error or OnException in the controller. I tried adding in the action, controller, area in the RedirectToAction route variable to no avail. I ended up renaming the POST action to EditPost and everything works now for me. Hope this helps.

public ActionResult Edit(int id)
{
    return View();
}

[HttpPost, ValidateAntiForgeryToken]
public ActionResult Edit(MyInputModel myInputModel)
{
    return View();
}

public ActionResult Create()
{
    return RedirectToAction("Edit", new {id = 1});
}
Kris Kilton
  • 938
  • 9
  • 11
0

I just came across this issue and nothing was working for me. It turned out the controller I was redirecting to required Authorization - the [Authorize] attribute was preventing any redirection

   [Authorize]//comment this out
   public class HomeController : Controller {...}

Because I forgot to add app.UseAuthentication() to the code block in the Startup.cs.

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
   ...
   app.UseHttpsRedirection();
   app.UseStaticFiles();
   app.UseAuthentication();
   app.UseMvc(routes =>
   ...

After adding the redirect began to work

PhiseySt
  • 92
  • 10