Created
July 5, 2013 09:17
-
-
Save benfoster/5933215 to your computer and use it in GitHub Desktop.
ASP.NET MVC Action Filter for automatic handling of Ajax requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net; | |
using System.Web.Mvc; | |
namespace Fabrik.Common.Web | |
{ | |
public class HijaxAttribute : ActionFilterAttribute | |
{ | |
public override void OnActionExecuting(ActionExecutingContext filterContext) | |
{ | |
if (CanBeHijaxed(filterContext)) | |
{ | |
var modelState = filterContext.Controller.ViewData.ModelState; | |
if (!modelState.IsValid) | |
{ | |
filterContext.Result = new JsonStatusCodeResult(modelState.ToSerializableDictionary(), HttpStatusCode.BadRequest); | |
} | |
} | |
} | |
public override void OnActionExecuted(ActionExecutedContext filterContext) | |
{ | |
if (CanBeHijaxed(filterContext)) | |
{ | |
var modelState = filterContext.Controller.ViewData.ModelState; | |
if (!modelState.IsValid) | |
{ | |
filterContext.Result = new JsonStatusCodeResult(modelState.ToSerializableDictionary(), HttpStatusCode.BadRequest); | |
} | |
else | |
{ | |
var result = filterContext.Result as RedirectResult; | |
if (result != null) | |
{ | |
var redirectUrl = UrlHelper.GenerateContentUrl(result.Url, filterContext.HttpContext); | |
filterContext.Result = new JavaScriptRedirectResult(redirectUrl); | |
} | |
else // just return an empty result - could maybe convert view model etc. | |
{ | |
filterContext.Result = new EmptyResult(); | |
} | |
} | |
} | |
} | |
private bool CanBeHijaxed(ControllerContext controllerContext) | |
{ | |
var request = controllerContext.RequestContext.HttpContext.Request; | |
return request.IsAjaxRequest() && request.HttpMethod == "POST"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment