I have a Concurrency check at my data layer that will threw a custom exception (ConcurrencyValidationException) when the condition occurs. I'm trying to display this as a friendly error message in my ValidationSummary object, like the other validation errors.
The problem is that I lose that invalid state when using RedirectToAction. I've tried passing through the ViewData state as TempData but it doesn't seem to work.
Here are the two actions in my controller:
public ActionResult Details(int? id)
{
StudentRepository studentRepository = StudentRepository();
Student student = new Student();
ActionResult result;
if (TempData["Student"] != null)
{
student = TempData["Student"] as Student;
TempData["Student"] = student; // needed to survive a browser refresh
}
else if (id != null)
student = studentRepository.GetById((int)id);
if (student != null)
result = View(student);
else
result = RedirectToAction("Index");
return result;
}
[HttpPut]
public ActionResult Upsert(Student model)
{
StudentRepository studentRepository = StudentRepository();
int studentId= 0;
try
{
if (model.IsValid() && model.Id == null)
{
studentId = studentRepository.Add(model);
}
else if (model.IsValid() && model.Id != null)
{
studentRepository.Update(model);
studentId = (int)model.Id;
}
}
catch (ConcurrencyValidationException exception)
{
ModelState.AddModelError("ConcurrencyUniqueID", exception);
TempData["Student"] = model;
if (model.Id != null)
studentId = (int)model.Id;
}
return RedirectToAction("Details", new { id = studentId });
}
When the Details View is loaded, no error is displayed, the error is lost. BTW, the reason I'm using RedirectToAction and not displaying calling View in Upsert() is that I don't want the URL to be /Upsert, I want it to be /Details/[id].
Updated: I can see that the student is properly preserved, but the added model validation isn't.