【发布时间】:2015-06-05 10:07:48
【问题描述】:
问题:
我想在成功时将部分视图加载到 DIV 中,但如果发生错误,我需要重定向到视图主页。问题是重定向到操作也被加载到 div resultdisplay 中。
如果出现错误,我应该如何管理错误处理以重定向到完整视图?
代码:
Ajax 调用:
function GetFilteredValuesCallback(values) {
var data = JSON.stringify(values);
var url = '/Controller/Action';
$.ajax({
type: 'GET',
url: url,
data: { filter: data },
success: function (result) {
$('#resultDisplay').html(result);
}
});
}
行动:
public ActionResult Action(string filter)
{
MyModel model = null;
try
{
// Do stuff with my model ...
throw new Exception("ERROR!");
}
catch (Exception ex)
{
// In case of error redirect to home page
return RedirectToAction("Index");
}
return PartialView("_PartialView", model);
}
【问题讨论】:
-
服务器端
RedirectToAction向浏览器返回重定向响应,然后 Ajax 会立即忽略该响应。您需要将元数据返回给您的 Ajax 调用,以便它知道将页面更改为新 URL(或者使用错误并在error:回调中重定向)。 -
Ajax 调用保持在同一页面上。与其捕获异常,不如让它发生,然后在 ajax
.fail()回调中使用location.href='yourUrl';
标签: javascript jquery ajax asp.net-mvc redirect