Here is the code in my Controller Action:
[HttpPost]
public JsonResult MyAction()
{
try
{
// Do something...
return Json(new { Success = true });
}
catch(Exception ex)
{
return Json(new { Error = ex.Message });
}
}
And, here is my script:
<script>
$.ajax({
type: "POST",
url: '@Url.Action("MyAction", "MyController")',
dataType: 'json'
}).done(function (data) {
alert(data.Success);
}
})
.fail(function (data) {
alert(data.Error);
});
</script>
This works on success (the alert correctly shows "true"), but when the action fails, alert(data.Error)
shows Undefined
.
Using FireBug, I can see that the JSON data is correctly returned. Why is data.Error
"Undefined" then?
UPDATE:
Here is the output from console.log(data)
:
readyState
4
responseText
"{"Error":"Attempted to divide by zero."}"
status
500
statusText
"Internal Server Error"
abort
function()
always
function()
complete
function()
done
function()
error
function()
fail
function()
getAllResponseHeaders
function()
getResponseHeader
function()
overrideMimeType
function()
pipe
function()
progress
function()
promise
function()
setRequestHeader
function()
state
function()
statusCode
function()
success
function()
then
function()
UPDATE 2:
Sorry, there was something wrong with my code (not the code here, but the code I was running). The correct output from console.log(data)
is this:
Object {Error="Some error."}