Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Created November 6, 2013 21:12
Show Gist options
  • Save saintc0d3r/7344163 to your computer and use it in GitHub Desktop.
Save saintc0d3r/7344163 to your computer and use it in GitHub Desktop.
[ASP .NET MVC] Maintain ModelState errors using ActionFilterAttributes when applying Post-Redirect-Get pattern.
using System;
using System.Diagnostics;
using System.IO;
using System.Web;
using System.Web.Mvc;
using DemoApp.Models;
using Infrastructure.WebMvc;
namespace DemoApp.Controllers
{
public class HomeController : Controller{
[HttpGet]
[RestoreModelStateFromTempData]
public ActionResult Index(){
ViewBag.SubmitResponse = TempData["SubmitResponse"];
return View();
}
[HttpPost]
[SetTempDataModelState]
public ActionResult Submit(NewUser newUser, HttpPostedFileBase imageFileUpload){
if (!ModelState.IsValid){
return RedirectToAction("index"");
}
try{
// Do process against the model (e.g. Store the model into database)
ModelState.Clear();
}
catch(Exception exception){
Trace.TraceError("Error message:'{0}'. Stack trace: '{1}'", exception.Message, exception.StackTrace);
ModelState.AddModelError(string.Empty, string.Format("Creating a new user is Failed. Reason: '{0}'", exception.Message));
}
return RedirectToAction("Index");
}
}
}
using System.Web.Mvc;
namespace Infrastructure.WebMvc
{
public class RestoreModelStateFromTempDataAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
if (filterContext.Controller.TempData.ContainsKey("ModelState"))
{
filterContext.Controller.ViewData.ModelState.Merge(filterContext.Controller.TempData["ModelState"] as ModelStateDictionary);
}
}
}
}
using System.Web.Mvc;
namespace Infrastructure.WebMvc
{
public class SetTempDataModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
filterContext.Controller.TempData["ModelState"] = filterContext.Controller.ViewData.ModelState;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment