我想在 ASP.NET MVC 3.0 中使用 JavaScript/jQuery/Ajax 从一个页面重定向到另一个页面。在按钮单击事件上,我编写了如下 JavaScript 代码。
function foo(id)
{
$.post('/Branch/Details/' + id);
}
我的 Controller 代码是这样的:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
当我点击一个按钮时,它会调用 BranchController 中的 Details 操作,但它不会返回到 Details View 。
我没有收到任何错误或异常。它在 Firebug 中显示状态 200 OK .我的代码有什么问题,如何重定向到详细信息 View 页面?
最佳答案
您没有在 $.post 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;
}
作为旁注: 你不应该像这样硬编码 url。在 ASP.NET MVC 应用程序中处理 url 时,您应该始终使用 url 帮助器。所以:
function foo(id) {
var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
关于c# - 使用 JavaScript/jQuery 重定向到 ASP.NET MVC 中的另一个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8148632/