In context of ASP.net MVC3, I have this line of code in a controller action, which tries to redirect to a particular url.
return Redirect(returnUrl);
returnUrl is a string that contains "/Home/Index/". For Some reason the redirect is not taking place and I remain on the same screen. I tried removing the trailing slash but no success. Any ideas why the Redirect does not take place?
The Redirect
method is intended to be used to redirect to external urls of your site and by passing it an absolute url. If you need to redirect to another controller action that belongs to your site it would be better to use this:
return RedirectToAction("Index", "Home");
This way you are no longer hardcoding urls and your code is less fragile to route changes.
This being said, if you are invoking the controller action that performs this redirect with AJAX you cannot expect it to redirect the browser anywhere => it will obviously stay on the same page. The AJAX request will succeed following all redirects and in the success callback you will get the final HTML of the /Home/Index
url as if it was requested without AJAX.
If you want to redirect in the success callback of an AJAX call you could have your controller action return for example a JSON object indicating the target url you want to redirect to:
return Json(new { redirectToUrl = Url.Action("Index", "Home") });
and in your callback use the window.location.href
function:
success: function(result) {
window.location.href = result.redirectToUrl;
}
If you are stuck on the SAME LOGIN SCREEN after supplying valid logon credentials, it is possible you have not set the Forms authentication cookie.
Whenever you use Redirect or RedirectToLocal in your Login actionmethods, make sure you call in the following order:
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToLocal(returnUrl);
This ensures, the cookie is set before Redirecting, otherwise the client will treat as if the user is not logged in.
Thanks
I had this same problem in MVC 5, the standard login.cshtml markup was working fine. I was only having problems when I was including the html markup for a template I had bought. So what I did was to start replacing the login.cshtml code bit by bit. As it turns out the problem was because the template included a JQuery plugin called "rd-mailform" and this was causing the issue.
This didn't work:
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "rd-mailform form-modern form-darker", role = "form" }))
And this worked:
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-modern form-darker", role = "form" }))
Sometimes designers that create these templates mix functionality with design, so you have to watch out for that.