bur*_*1ce 5 asp.net-mvc jquery
控制器:产品和动作:保存,返回JsonResult.如果发生了捕获异常,我想通过自定义错误消息向客户端(即:jQuery)发出错误信号.我怎样才能在服务器和客户端上做到这一点?我可以在这种情况下利用函数指针错误吗?
这是客户端代码
$.ajax({
url: '/Products/Save',
type: 'POST',
dataType: 'json',
data: ProductJson,
contentType: 'application/json; charset=utf-8',
error: function ()
{
//Display some custom error message that was generated from the server
},
success: function (data) {
// Product was saved! Yay
}
});
Run Code Online (Sandbox Code Playgroud)
error当请求失败时调用您引用的函数(意味着您的控制器操作未成功完成;例如,当用户发出请求时IIS已关闭).请参见http://api.jquery.com/jQuery.ajax/.
如果您的控制器操作已成功联系,并且您希望让客户端知道您的控制器操作中发生的错误,则应返回JsonResult包含客户端JS将理解的属性Error或ErrorCode属性的内容.
例如,您的控制器操作可能如下所示:
public ActionResult Save()
{
ActionResult result;
try
{
// An error occurs
}
catch(Exception)
{
result = new JsonResult()
{
// Probably include a more detailed error message.
Data = new { Error = true, ErrorMessage = "Product could not be saved." }
};
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
您将编写以下JavaScript来解析该错误:
$.ajax({
url: '/Products/Save',
'POST',
'json',
ProductJson,
'application/json; charset=utf-8',
error: function ()
{
//Display some custom error message that was generated from the server
},
success: function (data) {
if (data.Error) {
window.alert(data.ErrorMessage);
}
else {
// Product was saved! Yay
}
}
});
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
2177 次 |
| 最近记录: |