Handling Ajax cal exceptions via Custom Action Filters - asp.net-mvc

I am implementing an authorization mechanizm for my MVC application via Custom Action Filters.
I have provided the following Custom Action Filter for authorization:
[AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AuthorizationFilterAttribute : ActionFilterAttribute
{
public AuthorizationEntity Entity { get; set; }
public AuthorizationPermission Permission { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
AuthorizationResult result = null;
// Base actions (Authentication first)
base.OnActionExecuting(filterContext);
BaseController controller = filterContext.Controller as BaseController;
if (controller != null)
{ // Base actions (Authorizatioın next)
User usr = controller.currentUser;
AuthorizationResult ar = AuthorizationManager.GetAuthorizationResult(this.Entity, this.Permission, usr.UserId, usr.RoleId);
if (!ar.IsAuthorized)
{
throw new UnauthorizedAccessException(ar.Description);
}
// Authorized, continue
return;
}
}
}
And in my Base Controller class I am handling UnauthorizedAccessException type Exceptions and redirect them to a warning page via the following code
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception is UnauthorizedAccessException)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
filterContext.Result = new ViewResult()
{
ViewName = "UnauthorizedAccess"
};
}
else
{
throw filterContext.Exception;
}
}
}
This mechanism is OK for actions which return ActionResult. But I also have some AJAX calls, which I don't want to redirect to a warning page but would ilke to display a warning pop-up instead. Thi is why I have checked if the request is an Ajax call is not.
I am using the following code to make Ajax calls:
$.ajax({
type: "POST",
url: "AjaxPostMethodName",
dataType: "json",
data:
{
postval: [some value here]
},
success: function (msg) {
// Do some good actions here
},
error: function (x, t, m, b) {
// Display error
alert(m);
}
})
which goes to the following method on the Controller
public JsonResult AjaxPostMethodName(string postval)
{
try
{
// Some cool stuff here
return Json(null);
}
catch (Exception ex)
{
Response.StatusCode = UNAUTHORIZED_ACCESS_HTTP_STATUS_CODE;
return Json(ex.Message);
}
}
But when I fail the authorization check it directly shows the "Internal Server Error" message instead of falling to the catch block of AjaxPostMethodName method and displaying the proper message.
How can I make such code display filterContext.Exception instead of static "Internal Server Error" message?
Regards.

I finally found the answer to my solution in another Stack Overflow post (Can I return custom error from JsonResult to jQuery ajax error method?). I should use JsonExceptionFilterAttribute as follows:
public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
string msg = filterContext.Exception.Message;
if (filterContext.Exception.GetType() == Type.GetType("System.UnauthorizedAccessException"))
{
msg = "Unauthorized access";
}
filterContext.Result = new JsonResult
{
Data = new
{
errorMessage = msg
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}

Your OnException method will get called when there is Unhandled exception in your code. And in your ajax method AjaxPostMethodName you have put your code in try catch blcok. So any exception in this method will not go to your OnException method.

I've just checked the Response.StatusCode behavior and for me it works.
Index.cshtml
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript">
$(document).ready(function () {
alert('doc ready');
$.ajax({
type: "POST",
url: '#Url.Action("AjaxPostMethodName")',
dataType: "json",
data:
{
test: '10'
},
success: function (msg) {
// Do some good actions here
alert('success');
alert(msg);
},
error: function (x, t, m, b) {
// Display error
alert('error');
}
});
});
</script>
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AjaxPostMethodName(string postval)
{
Response.StatusCode = 401;
return Json("test");
}
}
}
When I set Response.StatusCode to 200 it calls success, when 401 it calls error.
Please verify whether other parts of your code don't interfere with it somehow.
You could try also following workaround - if AjaxPostMethodName throws exception returned JSON has a flag isValid and a message errorMessage, so in your ajax success method you can just check whether isValid is okay and handle error.

Related

MVC4 jQueryMobile won't show custom error page OnException

I'm trying to get a custom error page to display from a MVC4 Mobile Application but keep just getting the "Error Loading Page" yellow message being displayed instead of my custom page.
I have tried using the HandleErrorAttribute as below on Actions and Controllers with no success
[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")]
I have also tried overriding the OnException method of my base controller but this also doesn't appear to have any effect.
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
base.OnException(filterContext);
Logger.LogException(filterContext.Exception);
if (filterContext.Exception is SqlException)
{
filterContext.Result = new ViewResult { ViewName = "DatabaseError" };
}
if (filterContext.Exception is SomeOtherException)
{
filterContext.Result = new ViewResult { ViewName = "Error" };
}
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
filterContext.Result.ExecuteResult(this.ControllerContext);
}
}
If I try these methods on a non jQueryMobile MVC4 application they work as expected, just not in my mobile application!
Anyone have any insight as to why and how to make this work??
Ok so by disabling Ajax the appropriate error pages now get displayed!
In my _layout.cshtml page I added the following javascript:
$.mobile.ajaxEnabled = false;
You probably need to check in your filter if the request is via AJAX and return a JsonResult instead of a ViewResult, something like:
public class TypeSwitchingHandleErrorAttribute : HandleErrorAttribute
{
private static readonly string[] AJAX_ACCEPT_TYPES = new[] { "application/json", "application/javascript", "application/xml" };
private bool IsAjax(ExceptionContext filterContext)
{
return filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest"
||
filterContext.HttpContext.Request.AcceptTypes.ContainsAny(AJAX_ACCEPT_TYPES);
}
private void setResult(ExceptionContext filterContext, object content)
{
if( IsAjax(filterContext) )
{
filterContext.Result = new JsonResult { Data = content, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
} else
{
filterContext.Result = new ViewResult { ViewName = (string)content };
}
}
public override void OnException(ExceptionContext filterContext)
{
// your code...then where you set the result...
setResult(filterContext, "DatabaseError etc");
}
}
Then you'd have to interpret the ajax response appropriately on client-side. You could also send different content if it's an ajax request, like a standard {success: t/f, message: Exception.Message } object, and set the response status codes appropriately as well.

How do I Redirect to another Action/Controller in MVC3 from a VOID method?

I have a controller method that returns a void because it is building an Excel report for the user to download. The Excel 3rd party library we're using is writing to the response itself. The method looks something like this:
[HttpGet]
public void GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
excelReport.DownloadReport(System.Web.HttpContext.Current.Response);
}
catch (Exception ex)
{
// This is wrong, of course, because I'm not returning an ActionResult
Response.RedirectToRoute("/Report/Error/", new { exceptionType = ex.GetType().Name });
}
}
There are several security checks in place that throw exceptions if the user doesn't meet certain credentials for fetching the report. I want to redirect to a different page and pass along some information about the exception, but I can't figure out how to do this in MVC3....
Any ideas?
You could use the following code
Response.Redirect(Url.Action("Error", "Report", new { exceptionType = ex.GetType().Name }));
But have you taken a look at the FilePathResult or FileStreamResult ?
Instead of letting the 3rd part library write to the response directly get the content use regular ActionResult and return File(...) for the actual file or RedirectToAction(...) (or RedirectToRoute(...)) on error. If your 3rd party library can only write to Response you may need to use some tricks to capture it's output.
[HttpGet]
public ActionResult GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
var content = excelReport.MakeReport(System.Web.HttpContext.Current.Response);
return File(content, "application/xls", "something.xls");
}
catch (Exception ex)
{
RedirectToRoute("/Report/Error/", new { exceptionType = ex.GetType().Name });
}
}
You can return an EmptyActionResult:
[HttpGet]
public ActionResult GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
excelReport.DownloadReport(System.Web.HttpContext.Current.Response);
return new EmptyResult();
}
catch (Exception ex)
{
return RedirectToAction("Error", "Report", rnew { exceptionType = ex.GetType().Name });
}
}
Not sure if it works, haven't tested it.
Another approach would be using an exception filter:
public class MyExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var routeValues = new RouteValueDictionary()
{
{ "controller", "Error" },
{ "action", "Report" }
};
filterContext.Result = new RedirectToRouteResult(routeValues);
filterContext.ExceptionHandled = true;
// Or I can skip the redirection and render a whole new view
//filterContext.Result = new ViewResult()
//{
// ViewName = "Error"
// //..
//};
}
}

Handling session timeout in ajax calls

I'm making an ajax call using jquery to an asp.net mvc controller action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetWeek(string startDay)
{
var daysOfWeek = CompanyUtility.GetWeek(User.Company.Id, startDay);
return Json(daysOfWeek);
}
When session times out, this call will fail, as the User object is stored in session. I created a custom authorize attribute in order to check if session was lost and redirect to the login page. This works fine for page requests, however it doesn't work for ajax requests, as you can't redirect from an ajax request:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeUserAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.Request.IsAjaxRequest())
{//validate http request.
if (!httpContext.Request.IsAuthenticated
|| httpContext.Session["User"] == null)
{
FormsAuthentication.SignOut();
httpContext.Response.Redirect("~/?returnurl=" + httpContext.Request.Url.ToString());
return false;
}
}
return true;
}
}
I read on another thread that when the user isn't authenticated and you make an ajax request, you should set the status code to 401 (unauthorized) and then check for that in js and redirect them to the login page. However, I can't get this working:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Request.IsAjaxRequest() && (!Request.IsAuthenticated || User == null))
{
filterContext.RequestContext.HttpContext.Response.StatusCode = 401;
}
else
{
base.OnActionExecuting(filterContext);
}
}
Basically, it'll set it to 401, but then it'll continue into the controller action and throw an object ref not set to an instance of an object error, which then returns error 500 back to the client-side js. If I change my custom Authorize attribute to validate ajax requests as well and return false for those that aren't authenticated, that makes the ajax request return my login page, which obviously doesn't work.
How do I get this working?
You could write a custom [Authorize] attribute which would return JSON instead of throwing a 401 exception in case of unauthorized access which would allow client scripts to handle the scenario gracefully:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult
{
Data = new
{
// put whatever data you want which will be sent
// to the client
message = "sorry, but you were logged out"
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
then decorate your controller/actions with it and on the client:
$.get('#Url.Action("SomeAction")', function (result) {
if (result.message) {
alert(result.message);
} else {
// do whatever you were doing before with the results
}
});
I wouldn't change JsonRequestBehavior to AllowGet. Instead I suggest:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class MyAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
OnAuthorizationHelp(filterContext);
}
internal void OnAuthorizationHelp(AuthorizationContext filterContext)
{
if (filterContext.Result is HttpUnauthorizedResult)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.HttpContext.Response.End();
}
}
}
}
and add global js ajax errors handler:
$(document).ajaxError(function (xhr, props) {
if (props.status === 401) {
location.reload();
}
}
Even though this is well past answered, I think this is the shortest and sweetest answer if you are using .NET 4.5. Little property called SuppressFormsAuthenticationRedirect which was added. Set to true and it will not perform the 302 Redirect to login page.
http://msdn.microsoft.com/en-us/library/system.web.httpresponse.suppressformsauthenticationredirect.aspx
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// returns a 401 already
base.HandleUnauthorizedRequest(filterContext);
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// we simply have to tell mvc not to redirect to login page
filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
}
}
}
Assuming you plan on handling the ajax requests fail/error callback, in which you will get a 401 Unauthorized.
On Master page add this jquery script ------------
<script type="text/javascript">
$.ajaxSetup({
statusCode: {
403: function () {
window.location.reload();
}
}
});
OR
$.ajaxSetup({
error: function (x, e) {
if (x.status == 403) {
window.location.reload();
}
}
});
</script>
Add a cs file named with TraceFilter in your project and write a seald class TraceFilterAttribute inheriting to ActionFilterAttribute.
Add TraceFilterAttribute class in FilterConfig.cs available in App_Start folder of your project by writing below line.
filters.Add(new TraceFilterAttribute());
Override method OnActionExecuting() in TraceFilterAttribute class. This will automatically check session and if finds session null then calls script available in master page and from their you can go to your choice page.
[AttributeUsage(AttributeTargets.All)]
public sealed class TraceFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext != null)
{
HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session;
var userSession = objHttpSessionStateBase["etenetID"];
if (((userSession == null) && (!objHttpSessionStateBase.IsNewSession)) || (objHttpSessionStateBase.IsNewSession))
{
objHttpSessionStateBase.RemoveAll();
objHttpSessionStateBase.Clear();
objHttpSessionStateBase.Abandon();
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 403;
filterContext.Result = new JsonResult { Data = "LogOut" };
}
else
{
filterContext.Result = new RedirectResult("~/Admin/GoToLogin");
}
}
}
}
}
I was having a similar issue and found this
Instead of returning any JSON, just before the response is sent back, force ASP.NET to return a 401 code. In Global.asax:
protected void Application_EndRequest()
{
var context = new HttpContextWrapper(Context);
if (context.Request.IsAjaxRequest() && context.Response.StatusCode == 302)
{
Context.Response.Clear();
Context.Response.Write("**custom error message**");
Context.Response.StatusCode = 401;
}
}
Then you can let the client deal with it in JavaScript/jQuery or whatever you are using
here is how I handle this in so simple way in my custom authorization , I check if session is out and handle this as un-authorized with a boolean to check if it is really authenticated but not authorized (to redirect to un-authorized page) or it is not authenticated due to session time out ( redirect to Login)
private bool ispha_LoggedIn = false;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
ispha_LoggedIn = false;
var session = httpContext.Session;
bool authorize = false;
if (httpContext.Session["authenticationInfo"] == null)
{
return authorize;
}
using (OrchtechHR_MVCEntities db = new OrchtechHR_MVCEntities())
{
UserAuthenticationController UM = new UserAuthenticationController();
foreach (var roles in userAssignedRoles)
{
authorize = UM.IsUserInRole(httpContext.User.Identity.Name, roles);
if (authorize)
{
return authorize;
}
}
}
ispha_LoggedIn = true;
return authorize;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (ispha_LoggedIn==false)
{
filterContext.Result = new RedirectResult("~/UserAuthentication/LogIn");
}
else
{
filterContext.Result = new RedirectResult("~/Dashboard/UnAuthorized");
}
}
Hope if this guides someone and please if there're comments its appreciated to know them though.
You might want to try to throw HttpException and catch it in your javascript.
throw new HttpException(401, "Auth Failed")
on ajax call if session expired return something like this
<script>
$(function(){
location.reload();
});
</script>
haha...

Return special JsonResult in case of Exception occurs

public JsonResult Menu() { // Exception }
I need application not to redirect user to the 404 page, but return special JSON result like { "result":1 }.
I wonder, is there any another solution, not try-catching.
You can implement your own FilterAttribute similar to the HandleErrorAttribute.
The HandleErrorAttribute normally does a redirect when an error occurs, but you could implement a similar attribute that returns a JsonResult. Something like the following will do:
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
filterContext.Result = new JsonResult
{
Data = new { result = 1 },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.ExceptionHandled = true;
}
}
And then
[CustomHandleError]
public JsonResult Menu()
{
throw new Exception();
}
I would recommend that you download the MVC source code from CodePlex and inspect the current implementation of HandleErrorAttribute. It is a lot more subtle than my crude implementation above and you may want some of its functionality.

ASP.NET MVC Ajax Error handling

How do I handle exceptions thrown in a controller when jquery ajax calls an action?
For example, I would like a global javascript code that gets executed on any kind of server exception during an ajax call which displays the exception message if in debug mode or just a normal error message.
On the client side, I will call a function on the ajax error.
On the server side, Do I need to write a custom actionfilter?
If the server sends some status code different than 200, the error callback is executed:
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
and to register a global error handler you could use the $.ajaxSetup() method:
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
Another way is to use JSON. So you could write a custom action filter on the server which catches exception and transforms them into JSON response:
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
and then decorate your controller action with this attribute:
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
and finally invoke it:
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});
After googling I write a simple Exception handing based on MVC Action Filter:
public class HandleExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
filterContext.Exception.Message,
filterContext.Exception.StackTrace
}
};
filterContext.ExceptionHandled = true;
}
else
{
base.OnException(filterContext);
}
}
}
and write in global.ascx:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionAttribute());
}
and then write this script on the layout or Master page:
<script type="text/javascript">
$(document).ajaxError(function (e, jqxhr, settings, exception) {
e.stopPropagation();
if (jqxhr != null)
alert(jqxhr.responseText);
});
</script>
Finally you should turn on custom error.
and then enjoy it :)
Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);
And handle it as standard HTTP error on client as you like.
I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.
I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:
[HttpPut]
public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave)
{
if (!ModelState.IsValid)
{
return new JsonResult
{
Data = new { ErrorMessage = "Model is not valid", Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
try
{
MyDbContext db = new MyDbContext();
db.Entry(employeToSave).State = EntityState.Modified;
db.SaveChanges();
DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];
if (employeToSave.Id == user.Id)
{
user.Company = employeToSave.Company;
user.Language = employeToSave.Language;
user.Money = employeToSave.Money;
user.CostCenter = employeToSave.CostCenter;
Session["EmployeLoggin"] = user;
}
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { ErrorMessage = ex.Message, Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
return new JsonResult() { Data = new { Success = true }, };
}
Later in the ajax call I just asked for this property to know if I had an exception:
$.ajax({
url: 'UpdateEmployeeConfig',
type: 'PUT',
data: JSON.stringify(EmployeConfig),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.Success) {
//This is for the example. Please do something prettier for the user, :)
alert('All was really ok');
}
else {
alert('Oups.. we had errors: ' + data.ErrorMessage);
}
},
error: function (request, status, error) {
alert('oh, errors here. The call to the server is not working.')
}
});
Hope this helps. Happy code! :P
In agreement with aleho's response here's a complete example. It works like a charm and is super simple.
Controller code
[HttpGet]
public async Task<ActionResult> ChildItems()
{
var client = TranslationDataHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("childItems);
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
return Json(content, JsonRequestBehavior.AllowGet);
}
else
{
return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
}
}
}
Javascript code in the view
var url = '#Html.Raw(#Url.Action("ChildItems", "WorkflowItemModal")';
$.ajax({
type: "GET",
dataType: "json",
url: url,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Do something with the returned data
},
error: function (xhr, status, error) {
// Handle the error.
}
});
Hope this helps someone else!
For handling errors from ajax calls on the client side, you assign a function to the error option of the ajax call.
To set a default globally, you can use the function described here:
http://api.jquery.com/jQuery.ajaxSetup.

Resources