重定向到ASP.NET MVC另一个页面使用JavaScript / jQuery的 [英] Redirecting to another page in ASP.NET MVC using JavaScript/jQuery
问题描述
我想重定向从一个页面到ASP.NET MVC 3.0另一个页面使用JavaScript / jQuery的/阿贾克斯。在按钮单击事件我写的JavaScript code像下面。
I want to redirect from one page to another page in ASP.NET MVC 3.0 using JavaScript/jQuery/Ajax. On button click event I have written JavaScript code like below.
function foo(id)
{
$.post('/Branch/Details/' + id);
}
我的控制器code是这样的:
My controller code is like this:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
当我点击一个按钮,它是调用里面BranchController的细节动作,但它不返回到详细信息视图。
When I click on a button it is calling the Details action inside BranchController, but it doesn't return to the Details view.
我没有得到任何错误或异常。它的显示状态在萤火虫 200 OK。什么是错误的,我code和我怎样才能重定向到详细信息视图页面?
I didn't get any error or exception. It's showing status 200 OK in Firebug. What is wrong in my code and how can I redirect to the Details view page?
推荐答案
您不订阅任何成功回调到$ .post的AJAX调用。这意味着该请求被执行,但你什么都不做的结果。如果你想做一件事的结果是有用的,请尝试:
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
});
在另一方面,如果你想重定向,你绝对不需要AJAX。只有当你想留在同一页上,并更新只是它的一部分,你使用AJAX。
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.
所以,如果你只是想重定向浏览器:
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
作为一个方面说明:
你永远不应该被硬编码这样的URL。你应该总是在一个ASP.NET MVC应用程序的URL打交道时使用的网址助手。所以:
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);
}
这篇关于重定向到ASP.NET MVC另一个页面使用JavaScript / jQuery的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!