0

我有以下 GET Action 方法:-

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

我有以下 POST 操作方法:-

[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) ;}

::编辑::

我已将我的 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 错误之后仍然会显示旧的客户端值,而不是显示来自数据库的新值?你能就可能出现的问题提出建议吗?

4

1 回答 1

2

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

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

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

于 2013-07-13T16:15:45.023 回答