69 javascript c# asp.net-mvc jquery
我想使用JavaScript/jQuery/Ajax从ASP.NET MVC 3.0中的一个页面重定向到另一个页面.在按钮单击事件上,我编写了如下所示的JavaScript代码.
function foo(id)
{
$.post('/Branch/Details/' + id);
}
Run Code Online (Sandbox Code Playgroud)
我的控制器代码是这样的:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
Run Code Online (Sandbox Code Playgroud)
当我单击一个按钮时,它调用BranchController中的Details操作,但它不会返回Details视图.
我没有得到任何错误或异常.它在Firebug中显示状态200 OK .我的代码有什么问题,如何重定向到详细信息视图页面?
Dar*_*rov 137
您没有订阅$ .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
});
Run Code Online (Sandbox Code Playgroud)
另一方面,如果你想重定向,你绝对不需要AJAX.仅当您希望保持在同一页面并仅更新其中的一部分时,才使用AJAX.
因此,如果您只想重定向浏览器:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
Run Code Online (Sandbox Code Playgroud)
作为旁注:你永远不应该像这样硬编码网址.在ASP.NET MVC应用程序中处理URL时,应始终使用url帮助程序.所以:
function foo(id) {
var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
Run Code Online (Sandbox Code Playgroud)
Mri*_*dul 37
这可以通过在视图中使用隐藏变量然后使用该变量从JavaScript代码发布来完成.
这是我在视图中的代码
@Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
Run Code Online (Sandbox Code Playgroud)
现在您可以在JavaScript文件中使用它:
var url = $("#RedirectTo").val();
location.href = url;
Run Code Online (Sandbox Code Playgroud)
它对我来说很有魅力.我希望它对你也有帮助.
您可以使用:
window.location.href = '/Branch/Details/' + id;
Run Code Online (Sandbox Code Playgroud)
但是如果没有成功或错误函数,您的Ajax代码就不完整了.
// 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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
251686 次 |
| 最近记录: |