Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AjaxRedirectResult and AjaxRequestExtension
using System;
using System.Web;
using System.Web.Mvc;
/// <summary>
/// See http://stackoverflow.com/questions/1171035/asp-net-mvc-custom-error-handling-application-error-global-asax/5952774#5952774
/// for implementation details
/// </summary>
public class AjaxRedirectResult : RedirectResult {
public AjaxRedirectResult(string url, ControllerContext controllerContext)
: base(url) {
ExecuteResult(controllerContext);
}
public override void ExecuteResult(ControllerContext context) {
if (context.RequestContext.HttpContext.Request.IsAjaxRequest()) {
JavaScriptResult result = new JavaScriptResult() {
Script = String.Format(@"/*try{{history.pushState(null,null,window.location.href);}}
catch(err){{}}*/window.location.replace('{0}');",
UrlHelper.GenerateContentUrl(this.Url, context.HttpContext))
};
// Put the route data into temp data so we don't lose anything
context.Controller.TempData.Clear();
foreach (var item in context.RouteData.Values) {
context.Controller.TempData.Add(item.Key, item.Value);
}
result.ExecuteResult(context);
} else {
base.ExecuteResult(context);
}
}
}
public static class AjaxRequestExtension {
public static bool IsAjaxRequest(this HttpRequest request) {
return (request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment