以下是我正在寻找的行为:
我使用ASP.NET MVC 1.0作为主要框架,使用jQuery UI中的对话框组件,使用LINQ-to-SQL来处理数据库交互。第一步到第四步执行得很好。但是,第五步检索记录,但不删除它。第六步执行,但记录仍显示在列表中。
以下是删除链接的代码:
<% if (Model.CanDelete())
{ %>
<%= Html.ActionLink("Delete", "Delete", new { id = Model.Package_ID },
new { onclick = string.Format("deletePackage({0}); return false;", Model.Package_ID) })%> |
<% } %>
以下是onclick处理程序的代码:
function deletePackage(packageID) {
createDialogContent(); // The HTML for the dialog content is set in this method
$.getJSON('/Spectrum/Package/DetailsJSON/' + packageID, function(json) {
$('p.message').html('Delete <strong>' + json.Description + '</strong>?');
});
$('div.confirm').attr('title', 'Delete Package');
$('div.confirm').dialog({
draggable: false,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
resizable: false,
buttons: {
'Confirm': function() {
$(this).dialog('destroy').remove();
$.post('/Spectrum/Package/Delete/' + packageID);
// The next line used to be: $.get('/Spectrum/Package/Index');
window.location.href = '/Spectrum/Package/Index';
},
Cancel: function() {
$(this).dialog('destroy').remove();
}
}
});
}
以下是删除控制器方法的代码:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id)
{
Package package = RepositoryManager.Package().GetPackage(id);
PackageDeleteViewModel viewModel = new PackageDeleteViewModel
{
Package_ID = package.Package_ID
};
RepositoryManager.Package().PackageDelete(viewModel); // see code below
return new EmptyResult();
}
最后,这是删除的存储库方法:
public void PackageDelete(PackageDeleteViewModel data)
{
Package package = RepositoryManager.Package().GetPackage(data.Package_ID);
if (package.BrokerageOrderPackages.Count == 0
&& package.ManagementOrderPackages.Count == 0
&& package.Seeds.Count == 0)
{
db.Packages.DeleteOnSubmit(package); // This branch is being executed
db.SubmitChanges();
}
else
{
throw new RulesException("Package cannot be deleted.", "PackageDelete");
}
}
我不认为我在这里推动信封或过于花哨。一个值得关注的领域:在onclick方法的Confirm按钮处理程序中,第一个版本将成功删除记录,但不会重定向到Index视图。对于当前版本,删除会以静默方式失败,但会发生重定向。在这两种情况下,Firefox / Firebug报告指数GET为200。 Firefox和IE中的行为类似。
答案 0 :(得分:2)
$ .post是异步ajax请求,如果你重新加载页面,则会取消呼叫。您应该在其回调函数参数上重新加载页面:
$.post('/Spectrum/Package/Delete/' + packageID,
null,
function(json){
if (json.success) {
window.location.href = '/Spectrum/Package/Index';
} else {
// jquery dialog call or
alert(json.errorMessage);
}
},
'json');
控制器代码:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id)
{
try {
// Validation and deletion code
} catch exception ex {
return Json(new {errorMessage = ex.Message, success = false});
}
return Json(new {success = true});
}