Last active
December 2, 2015 13:23
-
-
Save donaldgray/aeac57ba310ef6b61598 to your computer and use it in GitHub Desktop.
ModelState Import/Export
This file contains 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
/// <summary> | |
/// Base class for Import/Export ModelState From/To TempData action filters | |
/// </summary> | |
public abstract class ModelStateTempDataAttribute : ActionFilterAttribute | |
{ | |
protected static readonly string Key = typeof(ModelStateTempDataAttribute).FullName; | |
} | |
/// <summary> | |
/// Import ModelState from previous ActionMethod from TempData | |
/// </summary> | |
/// <remarks>This allows the ModelState from one action result to be used in another ActionResult</remarks> | |
public class ImportModelStateAttribute : ModelStateTempDataAttribute | |
{ | |
public override void OnActionExecuted(ActionExecutedContext filterContext) | |
{ | |
ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary; | |
if (modelState != null) | |
{ | |
// Only import if we are viewing | |
if (filterContext.Result is ViewResult) | |
{ | |
filterContext.Controller.ViewData.ModelState.Merge(modelState); | |
} | |
else | |
{ | |
filterContext.Controller.TempData.Remove(Key); | |
} | |
} | |
base.OnActionExecuted(filterContext); | |
} | |
} | |
/// <summary> | |
/// Export ModelState from ActionMethod to TempData | |
/// </summary> | |
/// <remarks>This allows the ModelState from one action result to be used in another ActionResult</remarks> | |
public class ExportModelAttribute : ModelStateTempDataAttribute | |
{ | |
public override void OnActionExecuted(ActionExecutedContext filterContext) | |
{ | |
if (!filterContext.Controller.ViewData.ModelState.IsValid) | |
{ | |
// Export if we are redirecting | |
if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult)) | |
{ | |
filterContext.Controller.TempData[Key] = filterContext.Controller.ViewData.ModelState; | |
} | |
} | |
base.OnActionExecuted(filterContext); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment