Return controller error to JS (Jquery/Ajax)

Asked

Viewed 298 times

0

How to check error on a call return Jquery by ajax for a controller. This return did not come formatted as you would like, just checking the custom fields.

 $.ajax({
         type: "POST",
         dataType: "json",
         url: "MyController/Create",
         data: JSON.stringify(myObject),
         success: function (result) {
           if(result.error>0)
         {            
             alert("Error:" + result.ErrorMessage ); 
         }
      });

1 answer

0

A Way to send the error to the JS is to update the Status Code of the object response and customize an error msg for return.

Controller

public JsonResult Create(MyObject myObject) 
{
  //Tudo certo
  return Json(new { IsCreated = True, Content = ViewGenerator(myObject));

  //A inclusão não aconteceu mas não causou erro ao processo
  return Json(new { IsCreated = False, Content = ViewGenerator(myObject));  

  //Erro
  Response.StatusCode = (int)HttpStatusCode.InternalServerError;
  return Json(new { IsCreated = false, ErrorMessage = 'Minha MSG de erro');
}

JS

$.ajax({
     type: "POST",
     dataType: "json",
     url: "MyController/Create",
     data: JSON.stringify(myObject),
     success: function (result) {
       if(result.IsCreated)
     {
    //... Tudo certo
     }
     else
     {
    //... A inclusão não aconteceu mas não causou erro ao processo
     }
   },
    error: function (error) {
            alert("Erro:" + erro.responseJSON.ErrorMessage ); //Erro
        }
  });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.