问题
I'm calling an action in controller using Ajax, If The action is success it will return FileContentResult, if it fails i'm throwing exception. When throwing exception i'm sending a string and i want to show it as alert, but unable to extract the string (excep) out of the xmlHttpRequest.
The Exception thrown in the controller:
if (existInProgress)
{
excep = "Cannot create file, some orders are already in status In Progress.";
throw new Exception(String.Format(excep));
}
Ajax call:
$.ajax({
url: "OrderWarehouse/Export",
type: "POST",
data: pdata,
contentType: false,
success: function (data) {
swal("Success!", "Success!", "success").then((value) => { location.reload(); })
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var respJson = XMLHttpRequest.responseText;
var jsonexp = JSON.parse(respJson);
window.alert(jsonexp.data);
swal("Error!", "Error!", "error").then((value) => { location.reload(); })
}
});
Why Parse.JSON is not recognize there?
what other ways can i extract the text?
Thank you!
回答1:
It's not a right way to return exception messages to view. If you put breakpoint on your ajax call, you could inspect respJson
and why it couldn't be parsed. It's not the right format that you want.
error function is for some unhandled exception that we don't know about it like 500 ones. Handling our exceptions makes no sense.
I guess you don't need throwing the exception just returning some JSON object is enough
return Json(new { Success = false, Message = excep });
But throwing exception is inevitable, you could do it like below:
try {
if (existInProgress) {
var excep = "Cannot create file, some orders are already in status In Progress.";
throw new Exception(String.Format(excep));
}
return Json(new {
Success = true,
Status = yourModel
});
}
catch(Exception ex) {
return Json(new {
Success = false,
Message = ex.Message
});
}
来源:https://stackoverflow.com/questions/65010486/sending-string-in-controller-to-ajax-in-view