我想在ASP中从一个页面重定向到另一个页面.NET MVC 3.0,使用JavaScript/jQuery/Ajax.在button click事件中,我编写了如下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视图.

我没有收到任何错误或异常.它显示状态为Firebug分之200 OK.我的代码有什么问题,如何重定向到详细信息查看页面?

推荐答案

You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:

$.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
});

On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.

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

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

As a side note: You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:

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

Jquery相关问答推荐

将搜索面板和服务器端与POST AJAX请求一起使用时出现DataTables错误

:eq Jquery,我似乎无法显示第一个之后的元素

如果文本框内容在 X 秒内没有更改,则进行 post 调用

ASP.NET Core 6 jQuery 验证不起作用

使用带有 bootstrap 验证的 Ajax 函数时出现问题

$ 不是函数 - jQuery 错误

jQuery在点击函数后获取
  • 元素的id/value
  • 如何以十六进制获取元素的背景 colored颜色 代码?

    如何在 jQuery 中 Select 特定的表单元素?

    在 jQuery 事件中控制this的值

    JQuery通过类名获取所有元素

    Angular.js 在多个元素中重复

    如何使用 jQuery Select 的插件重置表单?

    Bootstrap 3.0 弹出框和工具提示

    使用 jQuery Select 最后 5 个元素

    如何阻止 Chrome 进入调试模式?

    使用 AJAX 加载 Bootstrap 弹出内容.这可能吗?

    使用 jQuery 的 ajax 方法将图像作为 blob 检索

    如何使用 JQuery $.scrollTo() 函数滚动窗口

    jquery - 成功时使用ajax结果返回值