Created
January 5, 2017 23:07
-
-
Save Jaecen/0839830f7b7dbb3dfdabf718d47404b6 to your computer and use it in GitHub Desktop.
Improved filters for POST redirect GET model state transfer.
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.Web.Mvc; | |
namespace AspDotNetStorefront.Filters | |
{ | |
public class SafeExportModelStateToTempData : ActionFilterAttribute | |
{ | |
public const string Key = "ExportedModelState"; | |
public override void OnActionExecuted(ActionExecutedContext filterContext) | |
{ | |
// Only export when ModelState is not valid | |
if(!filterContext.Controller.ViewData.ModelState.IsValid) | |
// Export if we are redirecting | |
if((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult)) | |
{ | |
var key = GenerateKey( | |
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, | |
filterContext.ActionDescriptor.ActionName); | |
filterContext.Controller.TempData[key] = filterContext.Controller.ViewData.ModelState; | |
} | |
base.OnActionExecuted(filterContext); | |
} | |
public static string GenerateKey(string controllerName, string actionName) | |
=> $"{Key}-{controllerName}-{actionName}"; | |
} | |
public class SafeImportModelStateFromTempData : ActionFilterAttribute | |
{ | |
public override void OnActionExecuting(ActionExecutingContext filterContext) | |
{ | |
var key = SafeExportModelStateToTempData.GenerateKey( | |
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, | |
filterContext.ActionDescriptor.ActionName); | |
var modelState = filterContext.Controller.TempData[key] as ModelStateDictionary; | |
if(modelState != null) | |
filterContext.Controller.ViewData.ModelState.Merge(modelState); | |
base.OnActionExecuting(filterContext); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment