Skip to content

Instantly share code, notes, and snippets.

@Jaecen
Created January 5, 2017 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jaecen/0839830f7b7dbb3dfdabf718d47404b6 to your computer and use it in GitHub Desktop.
Save Jaecen/0839830f7b7dbb3dfdabf718d47404b6 to your computer and use it in GitHub Desktop.
Improved filters for POST redirect GET model state transfer.
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