且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

重定向(URL)无法正常工作

更新时间:2023-10-21 14:01:22

重定向法的目的是用来重定向到您的网站的外部URL,并通过将其绝对URL。如果您需要重定向到属于你的网站会得到更好的使用该另一个控制器动作:

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");

这样,你不再是硬编码网址和code是路由变化不那么脆弱。

This way you are no longer hardcoding urls and your code is less fragile to route changes.

这是说,如果你调用控制器动作执行此与AJAX重定向你不能指望它来随时随地浏览器重定向=>这显然会留在同一页上。 AJAX请求将成功以下所有重定向和成功的回调,您将获得好像是要求没有AJAX /首页/指数网​​址的最终HTML

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.

如果你想在一个AJAX的成功回调重定向叫你可以有例如您的控制器动作返回一个JSON对象,指示要重定向到目标网址:

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") });

和在回调中使用 window.location.href 功能:

success: function(result) {
    window.location.href = result.redirectToUrl;
}