c# - 如何捕获可能的错误消息并将其转移到甜蜜警报
问题描述
在删除按钮上,我显示正常工作的甜蜜警报。问题是当我发送不存在的对象 id 时,我收到相同的消息(我成功删除)。
我想要的是在发生任何错误时显示一条消息(例如,找不到具有该 id 的事件,我想创建新消息并将其显示为一个甜蜜的警报)。
$('.deleteEvent').on('click', function () {
var $button = $(this);
var id = $button.data('id');
console.log("id", id);
var config = {
title: 'Are you sure',
type: 'info',
showCancelButton: true,
confirmButtonText: 'Yes',
cancelButtonText: ' No',
closeOnConfirm: false,
closeOnCancel: true
};
swal(config, function (isConfirm) {
if (isConfirm) {
console.log("lokac", window.location.origin);
var url = window.location.origin + '/events/delete?id=' + id;
$.post(url)
.done(function () {
var doneConfig = {
title: 'Succ....',
type: 'success',
confirmButtonText: 'Ok'
};
sweetAlert(doneConfig, function (done) {
if (done) {
window.location.reload();
}
});
})
.fail(function (error) {
var errorConfig = {
title: 'Not Found',
type: 'error',
confirmButtonText: 'Ok'
};
sweetAlert(errorConfig, function (done) {
if (done) {
window.location.reload();
}
});
});
}
});
});
还有我的控制器
public ActionResult Delete(int id)
{
if (id == default(int))
return RedirectToRoute(AppRoute.Events.EventsRoute);
id = -1;
try
{
var event =
DbContext.Event.FirstOrDefault(x => x.EventId == id);
if (event == null)
{
//If event is not found, I want to create a message which
//will be displayed on sweet alert
}
}
//.....
}
解决方案
考虑到执行失败函数的 HTTP 状态代码必须不同于 200 OK,因此例如,在您的控制器中,如果出现故障,您可以返回 HTTP 状态代码 500(内部服务器错误),它将执行失败函数。
在您的示例中必须类似于:
if (event == null)
{
//If event is not found, I want to create a message which
//will be displayed on sweet alert
return HttpStatusCodeResult(500)
}
如果您想显示不同的消息,您应该在 .done 和 .fail 函数中捕获 HTTP 状态代码,并根据您从服务器获得的内容显示一条消息
推荐阅读
- unity3d - 如何将文本元素捕捉到 Unity 中文本对象的父对象的边缘?
- oracle - 如何将我的 oracle 数据库导入到 oracle 云网站?
- opengl - Understanding buffer swapping in more detail
- android - 如何从 Android 应用访问 Chromebook 设置?
- javascript - 隐藏复选框并使标签可点击。JS
- python - 允许来自 python-flask swagger 应用程序的 JSON 响应中的空值?
- cmd - 您如何在 cmd 设置提示符中抑制用户响应?
- python - 如何在熊猫数据框中找到值已更改的行?
- css - 如何更改我在css中文本的颜色?
- typescript - ServerStack TypeScript JsonServiceClient COR 问题