Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MVC and JsonResult in case of error

In ASP MVC I have a controller that returns json data:

public JsonResult Edit(int? id)
{
   if(id==null)
   {
      Response.StatusCode = (int)HttpStatusCode.BadRequest;
      return Json(new { message = "Bad Request" }, JsonRequestBehavior.AllowGet);
   }

   car carTmp = db.car.Find(id);
   if (carTmp == null)
   {
      Response.StatusCode = (int)HttpStatusCode.NotFound;
      return Json(new { message = "Not Found" }, JsonRequestBehavior.AllowGet);
   }

   return Json(carTmp, JsonRequestBehavior.AllowGet);
}

I also have the following ajax request:

$.getJSON("Edit/" + data, function (result) {
            var car = result;
        })
        .error(function (error) {
            alert(error.message);
        })

Why, in case of success, in the result object I have the json object (i.e: I can access result.id, result.name ecc...) but in case of error, error.message is undefined? (I have the message into error.responseJson.message)

like image 232
Tom Avatar asked Dec 02 '25 09:12

Tom


1 Answers

You are setting the status code in the response as 404 so the error callback should be executed.

The problem is that the error callback is defined as function( jqXHR, textStatus, errorThrown ), where the jqxhr will have a responseJSON property.

You just need to change your code as:

$.getJSON("Edit/" + data, function (result) {
    var car = result;
})
.error(function (xhr) {
    alert(xhr.responseJSON.message);
})
like image 157
Daniel J.G. Avatar answered Dec 04 '25 23:12

Daniel J.G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!