How to report error to $.ajax without throwing exception in MVC controller?

前端 未结 7 561
天涯浪人
天涯浪人 2020-12-14 06:53

I have a controller, and a method as defined...

[HttpPost]
public ActionResult UpdateUser(UserInformation model){

   // Instead of throwing exception
   thr         


        
7条回答
  •  伪装坚强ぢ
    2020-12-14 07:19

    I use this Particular class for Ajax errors

    public class HttpStatusCodeResultWithJson : JsonResult
    {
        private int _statusCode;
        private string _description;
        public HttpStatusCodeResultWithJson(int statusCode, string description = null)
        {
            _statusCode = statusCode;
            _description = description;
        }
        public override void ExecuteResult(ControllerContext context)
        {
            var httpContext = context.HttpContext;
            var response = httpContext.Response;
            response.StatusCode = _statusCode;
            response.StatusDescription = _description;
            base.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            base.ExecuteResult(context);
        }
    }
    

    Status code is a custom HTTP Status Code and in a global Ajax Error Function I test it like:

    MyNsp.ErrorAjax = function (xhr, st, str) {
            if (xhr.status == '418') {
                MyNsp.UI.Message("Warning: session expired!");
                return;
            }
            if (xhr.status == "419") {
                MyNsp.UI.Message("Security Token Missing");
                return;
            }
            var msg = 'Error: ' + (str ? str : xhr.statusText);
            MyNsp.UI.Message('Error. - status:' + st + "(" + msg + ")");
            return;
        };
    

提交回复
热议问题