Created
February 13, 2013 07:51
-
-
Save wheelibin/4942963 to your computer and use it in GitHub Desktop.
Pass ModelState between actions - Allows you to do a redirect to the GET action and retain the ModelState after a failed update (instead of recreating the view model and potentially repeating yourself).
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
public abstract class ModelStateTempDataTransfer : ActionFilterAttribute | |
{ | |
protected static readonly string Key = typeof(ModelStateTempDataTransfer).FullName; | |
} | |
public class ExportModelStateToTempData : ModelStateTempDataTransfer | |
{ | |
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)) | |
{ | |
filterContext.Controller.TempData[Key] = filterContext.Controller.ViewData.ModelState; | |
} | |
} | |
base.OnActionExecuted(filterContext); | |
} | |
} | |
public class ImportModelStateFromTempData : ModelStateTempDataTransfer | |
{ | |
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.Result is RedirectResult)) | |
{ | |
filterContext.Controller.ViewData.ModelState.Merge(modelState); | |
} | |
else | |
{ | |
//Otherwise remove it. | |
filterContext.Controller.TempData.Remove(Key); | |
} | |
} | |
base.OnActionExecuted(filterContext); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment