gpt4 book ai didi

javascript - 错误时从 AJAX 调用重定向到 View

转载 作者:行者123 更新时间:2023-11-28 12:24:46 25 4
gpt4 key购买 nike

问题:我想在成功时将部分 View 加载到 DIV 中,但如果发生错误,我需要重定向到 View 主页。问题是重定向到操作也加载到 div resultdisplay 中。如果发生错误,我应该如何管理错误处理以重定向到完整 View ?

代码:

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

最佳答案

好吧,您可以将信息发送回客户端 ajax 请求并在此处处理重定向,而不是在 Controller 中重定向:

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

Controller

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");
}
});
}

Controller

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

关于javascript - 错误时从 AJAX 调用重定向到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30663857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com