刷新页面后,ModelState Error将继续显示

时间:2013-07-13 14:53:18

标签: asp.net-mvc entity-framework-4.1

我有以下GET Action方法: -

public ActionResult Edit(int id)
        {
             return View(groupRepository.Find(id));
        }

我有以下POST Action方法: -

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Group group)
        {

            try
            {
                if (ModelState.IsValid)
                {
                    AuditInfo auditinfo = repository.IntiateAudit(2, 2, User.Identity.Name, 2);



                    groupRepository.InsertOrUpdate(group);
                    groupRepository.Save();

                    repository.InsertOrUpdateAudit(auditinfo);

                    return RedirectToAction("Index");
                }
            }
            catch (DbUpdateConcurrencyException ex)
            {
                var entry = ex.Entries.Single();

                var clientValues = (Group)entry.Entity;

                ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                + "was modified by another user after you got the original value. The "
                + "edit operation was canceled and the current values in the database "
                + "have been displayed. If you still want to edit this record, click "
                + "the Save button again. Otherwise click the Back to List hyperlink."); }

但问题是,如果引发(DbUpdateConcurrencyException),那么在用户刷新页面后,ModelState错误将继续显示。

第二个问题是刷新后旧值将继续显示,而不是从数据库中查看更新的值。

但是如果我点击浏览器URL并点击“Enter”,那么错误将被删除,并且将从数据库中检索这些值,这与刷新页面不同。

最后,Find方法是: -

    public Group Find(int id)
            { return context.Groups.Find(id) ;}

:: EDIT ::

我已将我的POST EDIT操作方法更新为: -

   catch (DbUpdateConcurrencyException ex)
            {
                var entry = ex.Entries.Single();
                var databaseValues = (Group)entry.GetDatabaseValues().ToObject();
               entry.Reload();
                var clientValues = (Group)entry.Entity;

                ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                + "was modified by another user after you got the original value. The "
                + "edit operation was canceled and the current values in the database "
                + "have been displayed. If you still want to edit this record, click "
                + "the Save button again. Otherwise click the Back to List hyperlink.");
               // department.Timestamp = databaseValues.Timestamp;
                group.timestamp = databaseValues.timestamp;

但是在显示ModelState错误之后仍然会显示旧的客户端值,而不是显示数据库中的新值?你能就可能出现的问题提出建议吗?

1 个答案:

答案 0 :(得分:2)

没有Reload从数据库中获取当前值:

//...
catch (DbUpdateConcurrencyException ex)
{
    var entry = ex.Entries.Single();
    entry.Reload();
    //...
}
return View(group);
//...

如果您在浏览器中单击“刷新”,它将重复发送POST请求。这就像再次点击提交按钮。只要您没有浏览器表单中的当前值,您将再次遇到相同的并发异常。点击Url上的Enter将发送GET请求,因此将调用您的GET操作并加载和显示当前值。