Controller: Products and Action: Save, return a JsonResult. If a trapped exception occurs, i would like to signal that error to the client (ie:jQuery) with a custom error message. How can I do that both on the server and client? Can i utilize the function pointer error in this scenario?
Here's the client code
$.ajax({
url: '/Products/Save',
type: 'POST',
dataType: 'json',
data: ProductJson,
contentType: 'application/json; charset=utf-8',
error: function ()
{
//Display some custom error message that was generated from the server
},
success: function (data) {
// Product was saved! Yay
}
});
The error
function that you refer to is called when the request fails (meaning your controller action did not complete successfully; for example, IIS was down when the user made the request). See http://api.jquery.com/jQuery.ajax/.
If your controller action is successfully contacted and you want to let the client know that something happened inside your controller action that was erroneous, you should return a JsonResult
that contains an Error
or ErrorCode
property that your client side JS will understand.
For example, your controller action could look something like this:
public ActionResult Save()
{
ActionResult result;
try
{
// An error occurs
}
catch(Exception)
{
result = new JsonResult()
{
// Probably include a more detailed error message.
Data = new { Error = true, ErrorMessage = "Product could not be saved." }
};
}
return result;
}
And you would write the following JavaScript to parse that error:
$.ajax({
url: '/Products/Save',
'POST',
'json',
ProductJson,
'application/json; charset=utf-8',
error: function ()
{
//Display some custom error message that was generated from the server
},
success: function (data) {
if (data.Error) {
window.alert(data.ErrorMessage);
}
else {
// Product was saved! Yay
}
}
});
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With