问题:
我想在成功时将部分视图加载到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);
}
答案 0 :(得分:5)
您可以将信息发送回客户端ajax请求并在此处理重定向,而不是在控制器中重定向,如下所示:
function GetFilteredValuesCallback(values) {
var data = JSON.stringify(values);
var url = '/Controller/Action';
$.ajax({
type: 'GET',
url: url,
data: { filter: data },
success: function (result) {
if(result.message==="Failed")
location.href = "yoururl"
else
$('#resultDisplay').html(result);
},
error:function(result)
{
//handle any errors
}
});
}
<强>控制器强>
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
return Json(new{message="Failed"}, JsonRequestBehavior.AllowGet); //Send a message back
}
return PartialView("_PartialView", model);
}
<强>更新强>
感谢@StephenMuecke建议以更优雅的方式处理这个问题,可以按照以下方式完成:
<强> JS 强>
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);
},
error:function(result)
{
location.href("yoururl");
}
});
}
<强>控制器强>
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
return new HttpStatusCodeResult(500);
}
return PartialView("_PartialView", model);
}