ASP.NET MVC Ajax错误返回视图而不是ajax
发布时间:2020-12-16 07:19:38 所属栏目:asp.Net 来源:网络整理
导读:我正在通过 AJAX对一个方法进行ASP.NET MVC调用,错误会引发异常.我希望将异常的消息传递回客户端,我宁愿不必捕获异常.像这样的东西: [HttpPost]public ActionResult AddUser(User user) { if (UserIsValid(user)) { return Json(new { resultText = "Succes
我正在通过
AJAX对一个方法进行ASP.NET MVC调用,错误会引发异常.我希望将异常的消息传递回客户端,我宁愿不必捕获异常.像这样的东西:
[HttpPost] public ActionResult AddUser(User user) { if (UserIsValid(user)) { return Json(new { resultText = "Success!" }); } throw new Exception("The user was invalid. Please fill out the entire form."); } 我在我的firebug响应中看到一个HTML页面 <!DOCTYPE html> <html> <head> <title>"The user was invalid. Please fill out the entire form."</title> ..... 我不想被迫使用try catch块来执行此操作.有没有办法自动获取jQuery $(document).ajaxError(function(){}来读取此异常消息?这是不好的做法?我可以覆盖控制器OnException吗?或者我是否必须尝试/ catch并返回JSON? 像这样的东西会很好: $(document).ajaxError(function (data) { alert(data.title); }); 解决方法
您可以使用自定义过滤器执行此操作:
$(document).ajaxError(function(event,jqxhr) { console.log(jqxhr.responseText); }); – [HttpPost] [CustomHandleErrorAttribute] public JsonResult Foo(bool isTrue) { if (isTrue) { return Json(new { Foo = "Bar" }); } throw new HttpException(404,"Oh noes..."); } public class CustomHandleErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { var exception = filterContext.Exception; var statusCode = new HttpException(null,exception).GetHttpCode(); filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet,//Not necessary for this example Data = new { error = true,message = filterContext.Exception.Message } }; filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = statusCode; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; } } 有点受到这篇博文的启发:http://www.prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- MvcBuildViews真实与实体框架在ASP.NET MVC 2
- asp.net-mvc – 双值绑定问题
- asp.net – 如果禁用ViewState会发生什么
- asp.net – C#Web API模型绑定提供程序应如何工作?
- asp.net-mvc – mvc HtmlHelper DisplayFor函数如何从lambd
- asp.net – asp mvc“一个有潜在危险的Request.Form ……”
- ASP.net MVC v2 – 调试模型绑定问题 – BUG?
- 在UNC路径上安装ASP.NET应用程序,您认为这可能吗?
- asp.net – ajax中的Updatepanel总是运行page_load事件?
- asp.net-mvc – 如何在单个视图中使用两个表单
推荐文章
站长推荐
- asp.net-mvc-4 – Asp.NET MVC – DataAnnotatio
- asp.net-core – ASP.NET核心MVC应用程序设置
- asp.net-mvc – 当路由有多个值时如何构建RouteV
- asp.net-mvc – ASP .Net MVC中购物车的会话变量
- asp.net-mvc – ASP.Net和x86与x64
- 更改生成的ASP.Net ID?
- 想想就好:我感觉我欠下的代码,再写十年也写不完
- asp.net-mvc – 重用MVC视图同时显示数据和编辑数
- asp.net-mvc – 如何告诉Ninject绑定到它没有引用
- 在ASP.NET MVC中测试HtmlHelpers
热点阅读