I have a controller, and a method as defined...
[HttpPost] public ActionResult UpdateUser(UserInformation model){ // Instead of throwing exception throw new InvalidOperationException("Something went wrong"); // I need something like return ExecutionError("Error Message"); // which should be received as an error to my // $.ajax at client side... }
Problems with Exceptions
I need some easy way to report some custom http status to my $.ajax call so that it should result an error at client side, but I do not want to throw an error.
UPDATE
I cannot change client script because it becomes inconsistent with other data source.
So far, HttpStatusCodeResult should work but it's IIS that is causing the problem here. No matter what error message I set, tried all answers, still I receive default message only.
The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.
Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the . ajaxError() method are executed at this time. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
Open your Visual Studio and create a empty ASP.NET MVC application. Click on File -> New Project -> Web -> ASP.NET web application. From the next window Select template Empty and from Add folders and core reference choose MVC. Name it as AJAXCalls and click Ok.
Status code 0 means the requested url is not reachable.
This is where HTTP status codes come into play. With Ajax you will be able to handle them accordingly.
[HttpPost] public ActionResult UpdateUser(UserInformation model){ if (!UserIsAuthorized()) return new HttpStatusCodeResult(401, "Custom Error Message 1"); // Unauthorized if (!model.IsValid) return new HttpStatusCodeResult(400, "Custom Error Message 2"); // Bad Request // etc. }
Here's a list of the defined status codes.
What about returning an object back to your page and analyse that in your ajax
callback.
[HttpPost] public ActionResult UpdateUser(UserInformation model) { if (SomethingWentWrong) return this.Json(new { success = false, message = "Uuups, something went wrong!" }); return this.Json(new { success=true, message=string.Empty}); }
jQuery
$.ajax({ url: "...", success: function(data){ if (!data.success) { // do something to show the user something went wrong using data.message } else { // YES! } } });
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