我正在使用 ASP.Net mvc 4 进行开发。我的索引 View 中有一个删除功能。在用户继续删除项目之前,这是要执行的步骤
弹出一个确认对话框,使用 JavaScript 获取"is"或“否”答案。
如果用户说"is",我会从 Controller 调用删除操作
删除操作从数据库中删除项目
删除操作返回 'RedirectToAction ("Index");'
..假设 View 将使用最新更新进行更新
第 5 步是我的问题..它不起作用
这是我的代码
删除按钮
<a href="@Url.Action("DeleteFile", new { id = @item.Id })"
onclick = "return confirm2delete(this);"
class="btn btn-danger btn-sm"
data-toggle="tooltip" title="Delete File">
<i class="fa fa-trash-o"></i>
</a>
JavaScript
function confirm2delete(obj)
{
deleteLinkObj = $(this);
w2confirm("Are sure to delete this file ?")
.yes(function () {
$.get(obj.href, function (data) {
alert(data); // i checked ..this return the html page created from the delete action
window.open (data); // not the right approach ???
});
})
.no(function () {
alert("no");
result = false;
});
return false;
}
我的 Controller 中的删除操作
public ActionResult DeleteFile(int id)
{
FileUpload f = db.FileUploads.Find(id);
try
{
FileInfo dfile = new FileInfo(f.fileUrl);
if (dfile.Exists) { dfile.Delete(); }
fileUrl = f.FileUrl.Replace("Images/Uploads", "Images/Thumbnails");
FileInfo thumbnail= new FileInfo(fileUrl);
if (thumbnail.Exists) { thumbnail.Delete(); }
db.FileUploads.Remove(f);
db.SaveChanges();
}
catch (Exception ex)
{
}
return RedirectToAction("Index"); // or may i should return something else to make it work in javascript ???
}
希望大家能帮帮我。我几天来一直在寻找和尝试达到这个水平,我觉得是时候寻求一些帮助了。再多一点点。快到了。
最佳答案
Ajax 调用停留在同一页面中,因此调用 return RedirectToAction("Index");
是没有意义的(它不会重定向)。无论如何,都没有必要返回新 View 。相反,如果 Controller 成功删除了该项目,您可以从 DOM 中删除现有元素。您尚未显示您的 View ,但假设您有一个表,其中一行可能类似于
<tr>
<td>the name of the file</td>
<td>the delete link</td>
</td>
然后您可以在“删除”链接所在的位置使用以下内容
<td><button type="button" class="delete" data-id="@item.Id">Delete</button></td>
关键点是 class
和 data-id
属性 - 修改其余部分以适合您的显示,但删除 onclick
属性(停止用行为污染你的标记并使用 unobtrusive javascript - 这是 21 世纪!)
然后是脚本
var url = '@Url.Action("DeleteFile")';
$('.delete').click(function() {
var id = $(this).data('id');
var row = $(this).closest('tr'); // modify if the containing element is not a <tr>
w2confirm("Are sure to delete this file ?")
.yes(function () {
$.post(url, { id: id }, function(response) { // its a POST, not a GET!
if (response) {
row.remove(); // remove the row
} else {
// Oops, something went wrong
}
}).fail(function (response) {
// Oops, something went wrong
});
})
.no(function() {
alert("no");
});
});
请注意,如果您使用 jquery 1.9+ 版本,则不需要 $.post()
函数中的 else
block ,因为 return Json(null);下面方法中的
将进入.fail()
回调
然后在 Controller 中,返回json表示该项已成功删除
[HttpPost]
public ActionResult DeleteFile(int id)
{
FileUpload f = db.FileUploads.Find(id);
try
{
....
db.SaveChanges();
return Json(true); // signal success
}
catch (Exception ex)
{
return Json(null); // signal failure
}
}
关于javascript - 如何从 javascript 打开操作调用的 View 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30386451/