I'm trying to fill Field with user information using ajax. It work well;
ACTION
public Operatore User(int Id)
{
Operatore User = new Operatore();
/*
DO STUFF TO FILL USER
*/
/*if something go wrong
throw new Exception("user does not exist");
*/
return User;
}
but if i throw Exception with custom message i can't read it in Ajax
AJAX
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "@Url.Action("User")",
data: { Id: $("#ID").find(":selected").val()},
success: function (msg) {
/*FILL THE DATA*/
/*It works well*/
},
error: function (error) {
alert(error.Message);
/*this does not work*/
}
});
I just need to read my custom error message. The alert return "undefined" How can i do?
If something goes wrong (in operatore):
Response.StatusCode = 500;
Return Json("Error Message");
StatusCode is necessary to mislead Ajax. Beware your action must return an object.
In Ajax:
error: function (error) {
alert(error.responseJSON);
}