我在我的数据层进行了并发检查,在条件发生时会抛出自定义异常(ConcurrencyValidationException)。我试图在我的ValidationSummary对象中将其显示为友好的错误消息,就像其他验证错误一样。
问题是我在使用RedirectToAction时失去了无效状态。我已经尝试将ViewData状态作为TempData传递,但它似乎不起作用。
以下是我的控制器中的两个操作:
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 });
}
加载详细信息视图时,不会显示错误,错误将丢失。顺便说一下,我使用RedirectToAction并且没有在Upsert()中显示调用View的原因是我不希望URL为/ Upsert,我希望它是/ Details / [id]。
更新: 我可以看到学生得到了妥善保存,但增加的模型验证却没有。
答案 0 :(得分:1)
TempData仅适用于一次访问,之后会删除其内容。所以这段代码是你的主要问题:
if (TempData["Student"] != null) // data is accessed and deleted
{
// oopss.. nothing in TempData now
student = TempData["Student"] as Student;
TempData["Student"] = student; // needed to survive a browser refresh
}
因此,您需要首先获取TempData并将其分配给某个东西,然后检查该变量:
var student = TempData["Student"] as Student;
if (student != null) // we're ok now
{
//....
}