【问题标题】:How can I redirect to a URL?如何重定向到 URL?
【发布时间】:2011-08-08 16:11:50
【问题描述】:
如何将查看器重定向到 URL?
我注意到有人问How to redirect to another webpage in JavaScript/jQuery?,但我不确定这应该去哪里。
我在控制器中尝试过:
window.location.replace("http://192.168.1.109/MWT/Taglist/ShowMap" + LastId);
并在视图中:
<% if (BreakCount >= 8) {
var url = "http://192.168.1.109/MWT/Taglist/ShowMap" + LastId;
window.location.replace(url);
} %>
这些都不起作用。在这两个地方,window 下方都有一条红色波浪线,当我将鼠标悬停在它上面时,消息显示“当前上下文中不存在名称 'window'。”
任何帮助都将非常感激!
=D
【问题讨论】:
标签:
asp.net-mvc-3
redirect
【解决方案1】:
您的问题被标记为 MVC 3,因此尽管您列出了 JavaScript 示例,我仍会为您提供答案。在您的控制器类中使用以下代码:
public ActionResult MyAction()
{
// Use this for an action
return RedirectToAction("ActionName");
// Use this for a URL
return Redirect("http://192.168.1.109/MWT/Taglist/ShowMap" + LastId);
}
这发生在服务器上,这意味着客户端浏览器收到重定向响应,浏览器可能会为此提交额外请求。如果您返回一个带有 JavaScript 的页面,它将必须加载一个页面,运行 JavaScript(假设它在客户端的浏览器上启用),然后加载下一页。除其他问题外,使用 JavaScript 意味着如果用户按下后退按钮,他们将被反复重定向回他们当前所在的页面。
【解决方案2】:
在你的控制器内部调用return RedirectToAction()。
public ActionResult MyAction() {
return RedirectToAction("Index", "Home");
}
或者,你使用T4MVC(你应该;-))
public ActionResult MyAction() {
return RedirectToAction(MVC.Home.Index());
}
不要将if 语句放在视图中 - 这不是 MVC 方式。控制器负责决定是否重定向到不同的视图。
【解决方案3】:
试试这样:
<script type="text/javascript">
// Make sure the LastId variable is defined
var LastId = '123';
<% if (BreakCount >= 8) { %>
var url = "http://192.168.1.109/MWT/Taglist/ShowMap" + LastId;
window.location.replace(url);
<% } %>
</script>
【解决方案4】:
试试这个:
<script type="text/javascript">
var id = '123';
location.href = "http://192.168.1.109/MWT/Taglist/ShowMap/" + id;
</script>
【解决方案5】:
试试这样:
top.location.href = "/url";