c# - 使用 JavaScript/jQuery 重定向到 ASP.NET MVC 中的另一个页面

标签 c# javascript jquery asp.net-mvc

我想在 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/

相关文章:

c# - 尽管使用了 Image.Dispose,但图像查看器内存不足

javascript - react /Redux : separating presentational and container components dilemma.

javascript - 谷歌浏览器扩展程序中长时间运行的任务

javascript - jQuery 获取 load() 函数的新结果

c# - 为什么跨线程UI组件调用没有EndInvoke?

c# - 如何保证打开同一个网站的新浏览器窗口时Session ID不会过期?

c# - 处理点击ListView的子项

javascript - HTML 文件的国际化

javascript - 模式不适用于 ie8

javascript - jquery json解析