If I have the following in my view:
$.ajax({
url: '@PathHelper.FullyQualifiedApplicationPath(Request)' + 'Home/asdasd',
type: 'POST', dataType: 'json',
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
data: {
searchForIt: document.getElementById('searchValue').value
},
error: OnError,
success: function (data) {
// Do Stuff
}
});
and the error function OnError is:
function OnError(xhr, errorType, exception) {
var responseText;
$("#dialog").html("");
try {
responseText = jQuery.parseJSON(xhr.responseText);
$("#dialog").append("<div><b>An error has occurred, please inform Paul Zahra quoting the following details:</b></div>");
$("#dialog").append("<div><b>" + errorType + " " + exception + "</b></div>");
$("#dialog").append("<div><u>Exception</u>:<br /><br />" + responseText.ExceptionType + "</div>");
$("#dialog").append("<div><u>StackTrace</u>:<br /><br />" + responseText.StackTrace + "</div>");
$("#dialog").append("<div><u>Message</u>:<br /><br />" + responseText.Message + "</div>");
} catch (e) {
responseText = xhr.responseText;
$("#dialog").html(responseText);
}
}
In the controller how do I set the parameters of the JSon error so that I can give custom details such as "You entered invalid data." or "The database has a fit, please try again."?;
OnError(xhr, errorType, exception)
P.S. In the controller in order to get ajax in the view to think an error has occured I merely use:
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
P.P.S. I know the following but it doesn't explain how I set it from an mvc controller.
"error Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."
"For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:
readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
statusCode()
abort()"