I have some code that saves a ticket in our system. If there is an error it does a RedirectToAction. The problem is that I don\'t seem to have my errors in the new action.
What I did to maintain my ModelState no matter where I go with redirects is the following:
In your model, add:
public ModelStateDictionary modelstate { get; set; }
In your model's constructor, add:
this.modelstate = new System.Web.Mvc.ModelStateDictionary();
Sample Post with my model called Models.ContactInformation:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult contact(Models.ContactInformation con)
{
if (string.IsNullOrEmpty(con.SelectedAgencySelectorType))
{
ModelState.AddModelError("", "You did not select an agency type.");
}
con.modelstate = ModelState;
TempData["contact"] = con;
if (!ModelState.IsValid) return RedirectToAction("contactinformation", "reports");
//do stuff
return RedirectToAction("contactinformation", "reports");
}
So now your tempdata has your model and modelstate as is.
The following is my view that is agnostic to the state of anything, unless it has something. Here's the code:
[HttpGet]
public ActionResult contactinformation()
{
//try cast to model
var m = new Models.ContactInformation();
if (TempData["contact"] is Models.ContactInformation) m = (Models.ContactInformation)TempData["contact"];
//restore modelstate if needed
if (!m.modelstate.IsValid)
{
foreach (ModelState item in m.modelstate.Values)
{
foreach (ModelError err in item.Errors)
{
ModelState.AddModelError("", err.ErrorMessage.ToString());
}
}
}
return View(m);
}