2

I have a MVC4 application where I call a controller action from javascript using jQuery. When an exception occurs in the controller the returned response text is in HTML format. I want it to be in JSON format. How can this be achieved?

I thought some JSON formatter should do the magic on its own...

JavaScript

// Call server to load web service methods
$.get("/Pws/LoadService/", data, function (result) {
    // Do stuff here
}, "json")
.error(function (error) { alert("error: " + JSON.stringify(error)) });

.Net Controller Action

[HttpGet]
public JsonResult LoadService(string serviceEndpoint)
{
    // do stuff that throws exception

    return Json(serviceModel, JsonRequestBehavior.AllowGet);            
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Andreas
  • 659
  • 6
  • 17

1 Answers1

3

Actually, the error you would be tracking in the error function is related to the request and not the application's error

So i would pass the error details in the Json result, somthing like that :

try {
 //....
    return Json(new {hasError=false, data=serviceModel}, JsonRequestBehavior.AllowGet); 
}
catch(Exception e) {
    return Json(new {hasError=true, data=e.Message}, JsonRequestBehavior.AllowGet); 
}

And in the client, you can handle with something like that :

$.get("/Pws/LoadService/", data, function (result) {

    var resultData = result.d;
    if(resultData.hasError == true) {
      //Handle error as you have the error's message in resultData.data
    }
    else {
        //Process with the data in resultData.data
    }
}, "json") ...
hemma731
  • 148
  • 1
  • 1
  • 8
  • This is the way I have solved this before. I thought that the framework would return exceptions in Json format when specifying JsonResult as return type. Perhaps I can set http header to application/json and get a Json result? I set this to an answer because I think it is a well known solution. – Andreas May 25 '13 at 09:26