【发布时间】:2012-03-31 10:24:07
【问题描述】:
我的 asp.net MVC 应用程序中有以下视图,其中包含用于删除对象的 ajax.actionlink:-
<table id="incrementanswer">
<tr>
<th>
Description
</th>
<th>
Answer
</th>
<th></th>
</tr>
@foreach (var answer in Model.Answers.OrderBy(a => a.IsRight))
{
<tr id = @answer.AnswersID>
<td>
@Html.DisplayFor(modelItem => answer.Description)
</td>
<td>
@Html.DisplayFor(modelItem => answer.Answer_Description.description)
</td>
<td>
@{ string i = "Are uou sure you want to delete " + @answer.Description.ToString() + " ?";}
@Ajax.ActionLink("Delete", "Delete", "Answer",
new { id = answer.AnswersID },
new AjaxOptions
{
Confirm = i,
HttpMethod = "Post",
OnBegin = string.Format(
"disablelink({0})",
Json.Encode(answer.AnswersID)),
OnSuccess = string.Format(
"deleteconfirmation3({0},{1})",
Json.Encode(answer.AnswersID), Json.Encode(answer.Description))
}) </td>
</tr>}</table>
以及将由上述 ajax 链接调用的以下 post delete 操作方法:-
[HttpPost]
public void Delete(int id)
{ var a = repository.FindAnswer(id);
repository.DeleteAnswer(a);
repository.Save();}
以及以下 OnSuccess 脚本:-
function deleteconfirmation3(rid, rname) {
$('#' + rid).remove();
jAlert(rname + ' Was Deleted Succsfully succsfully', 'Deletion Confirmation');}
目前,如果两个用户访问同一个视图,然后他们都点击了与同一个对象关联的删除链接,那么其中一个请求将引发空异常;那么我如何在操作方法端和视图端处理这个问题以向用户显示友好的消息;在这两种情况下:-
-
var a = repository.FindAnswer(id);返回 null 例外? - 或者
repository.Save();没有删除任何记录?
BR
编辑:-
我将发布操作方法更新为以下内容:-
[HttpPost]
public ActionResult Delete(int id)
{
try
{
Thread.Sleep(1000);
var a = repository.FindAnswer(id);
repository.DeleteAnswer(a);
repository.Save();
return Json(new { IsSuccess = "True", id = id, description = a.Description }, JsonRequestBehavior.AllowGet);
}
catch (ArgumentNullException) {
return Json(new { IsSuccess = "False" }, JsonRequestBehavior.AllowGet); }}
在视图上我将 ajax.actionlink 更新为以下内容:-
@{ string i = "Are uou sure you want to delete " + @answer.Description.ToString() + " ?";}
@Ajax.ActionLink("Delete", "Delete", "Answer",
new { id = answer.AnswersID },
new AjaxOptions
{
//OnBegin = "deleteconfirmation1",
Confirm = i,
HttpMethod = "Post",
OnBegin = string.Format(
"disablelink({0})",
Json.Encode(answer.AnswersID)),
OnSuccess = "myresponse"
})
和 Onsuccess 脚本:-
function myresponse(data) {
if (data.IsSuccess == "True")
{
$('#' + data.id ).remove();
jAlert(data.description + ' Was Deleted Succsfully succsfully', 'Deletion Confirmation');
}
else {
$('#' + data.id).remove();
jAlert(data.description + 'record has already been deleted', 'aaaa');
}
}
上面的代码在我测试时运行良好,但是这种方法听起来可以接受吗,因为我以前没有写过类似的东西? BR
【问题讨论】:
-
我不认为这是开发一些事务以允许仅通过一个浏览器窗口打开一个数据项的意义。这个问题的目标是什么?并发问题总是与更新操作而不是删除有关。如果用户尝试删除已删除的项目,只需向他显示消息,这不会损害您的业务逻辑。
-
在我的应用程序中,多个用户将有权删除同一个对象。因此,即使该对象已被其他用户删除,向用户返回消息已成功删除对象也可能会导致一些不一致问题 ....
标签: asp.net-mvc-3 jquery concurrency