使用 JavaScript/jQuery 在 ASP.NET MVC 中重定向到另一个页面

我想在 ASP.NET MVC 3.0中使用 JavaScript/jQuery/Ajax 从一个页面重定向到另一个页面。在按钮单击事件中,我编写了如下 JavaScript 代码。

function foo(id)
{
$.post('/Branch/Details/' + id);
}

我的控制器代码是这样的:

public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}

当我单击一个按钮时,它正在调用 BranchController 中的 Details 操作,但是它不返回 Details 视图。

我没有得到任何错误或异常。纵火犯显示状态200 OK。我的代码出了什么问题? 我如何重定向到 Details 视图页面?

323975 次浏览

您没有在 $中订阅任何成功回调。后 AJAX 呼叫。意味着执行了请求,但是对结果不做任何操作。如果你想对结果做些有用的事情,试试:

$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});

另一方面,如果你想重定向,你绝对不需要 AJAX。只有当您希望停留在同一个页面上并且只更新其中的一部分时,才使用 AJAX。

因此,如果你只想重定向浏览器:

function foo(id) {
window.location.href = '/Branch/Details/' + id;
}

顺便说一句: 你永远不应该硬编码这样的网址。在 ASP.NET MVC 应用程序中处理 url 时,应该始终使用 url 助手。所以:

function foo(id) {
var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}

你可使用:

window.location.href = '/Branch/Details/' + id;

但是如果没有成功或错误函数,Ajax 代码就是不完整的。

这可以通过在视图中使用一个隐藏变量,然后使用该变量从 JavaScript 代码中发布来实现。

这是我在视图中的代码

@Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));

现在您可以在 JavaScript 文件中使用它:

 var url = $("#RedirectTo").val();
location.href = url;

它对我很有效,我希望它对你也有帮助。

<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');


if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '@Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}


</script>
// in the HTML code I used some razor
@Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));


// now down in the script I do this
<script type="text/javascript">


var url = $("#RedirectTo").val();


$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>

检查下面的代码,这会对你有所帮助:

<script type="text/javascript">
window.opener.location.href = '@Url.Action("Action", "EventstController")', window.close();
</script>