RedirectToAction not changing URL or navigating to Index view
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.
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");
}
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.
Try as below:
return in your action:
return Json(Url.Action("Index", "Home"));
and in your ajax:
window.location.href