I am trying to redirect from controller action to another controller action like below:
public class LoginController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult RedirectToRegister()
{
return RedirectToAction("Index", "Register");
}
}
public class RegisterController : Controller
{
public ActionResult Index()
{
return View();
}
}
I have Url in my cshtml page like below:
<script type="text/javascript">
var LoginRedirectToRegisterUrl = '@Url.Action("RedirectToRegister", "Login")';
</script>
and I am calling from js like below:
function CallRedirectToRegister() {
window.location = LoginRedirectToRegisterUrl;
}
But it is not redirecting me to Register Page. My routing is like below:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
);
}
Where am I doing wrong?
答案 0 :(得分:0)
The server-side redirection looks fine, but your client-side call not so much: $.post(LoginRedirectToRegisterUrl);
starts an AJAX call to the URL. It does not change the current page. For that use this:
function CallRedirectToRegister() {
window.location = LoginRedirectToRegisterUrl;
}
This will issue an HTTP GET request. You need to remove the [HttpPost]
attribute from your action for this to work. If you can't do that you have to put a HTML form on your page and submit that to get a POST request. Something like this:
function CallRedirectToRegister() {
$('<form id="redirectForm">').attr('method', 'post').attr('action', LoginRedirectToRegisterUrl).appendTo($('body')).submit();
}
答案 1 :(得分:0)
Ajax调用不会重定向到页面。而不是ajax调用,使用
window.location = LoginRedirectToRegisterUrl;
并且无法重定向到POST方法,因为HTTP不支持使用POST重定向到页面。