I do not rebuild it because I do not stay at POST. I follow the POST-REDIRECT-GET pattern, so if I send a message to / User / Edit / 1 using the HTTP POST method, I will be redirected to / User / Edit / 1 uasing GET.
ModelState ported to TempData to follow Post-Redirect-Get and be available when calling GET. The view model is built in one place, when calling GET. Example:
[HttpPost] [ExportModelStateToTempData] public ActionResult Edit(int id, SomeVM postedModel) { if (ModelState.IsValid) { //do something with postedModel and then go back to list return RedirectToAction(ControllerActions.List); } //return back to edit, because there was an error return RedirectToAction(ControllerActions.Edit, new { id }); } [ImportModelStateFromTempData] public ActionResult Edit(int id) { var model = //create model here return View(ControllerActions.Edit, model); }
This is the code to import / export ModelState attributes:
public abstract class ModelStateTempDataTransferAttribute : ActionFilterAttribute { protected static readonly string Key = typeof(ModelStateTempDataTransferAttribute).FullName; } public class ExportModelStateToTempDataAttribute : ModelStateTempDataTransferAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) {
source share