Skip to content

Instantly share code, notes, and snippets.

@wheelibin
Created February 13, 2013 07:51
Show Gist options
  • Save wheelibin/4942963 to your computer and use it in GitHub Desktop.
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).
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