Return JSON with error status code MVC

前端 未结 11 1745
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 13:23

I was trying to return an error to the call to the controller as advised in This link so that client can take appropriate action. The controller is called by javascript via

11条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 14:06

    A simple way to send a error to Json is control Http Status Code of response object and set a custom error message.

    Controller

    public JsonResult Create(MyObject myObject) 
    {
      //AllFine
      return Json(new { IsCreated = True, Content = ViewGenerator(myObject));
    
      //Use input may be wrong but nothing crashed
      return Json(new { IsCreated = False, Content = ViewGenerator(myObject));  
    
      //Error
      Response.StatusCode = (int)HttpStatusCode.InternalServerError;
      return Json(new { IsCreated = false, ErrorMessage = 'My error message');
    }
    

    JS

    $.ajax({
         type: "POST",
         dataType: "json",
         url: "MyController/Create",
         data: JSON.stringify(myObject),
         success: function (result) {
           if(result.IsCreated)
         {
        //... ALL FINE
         }
         else
         {
        //... Use input may be wrong but nothing crashed
         }
       },
        error: function (error) {
                alert("Error:" + erro.responseJSON.ErrorMessage ); //Error
            }
      });
    

提交回复
热议问题