2

我有一个 MVC4 应用程序,我在其中使用 jQuery 从 javascript 调用控制器操作。当控制器中发生异常时,返回的响应文本为 HTML 格式。我希望它采用 JSON 格式。如何做到这一点?

我认为一些 JSON 格式化程序应该自己发挥作用......

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 控制器动作

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

    return Json(serviceModel, JsonRequestBehavior.AllowGet);            
}
4

1 回答 1

3

实际上,您将在错误函数中跟踪的错误与请求有关,而不是与应用程序的错误有关

所以我会在 Json 结果中传递错误详细信息,如下所示:

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

在客户端,您可以处理类似的事情:

$.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") ...
于 2013-05-23T09:29:02.893 回答