我有一张照片,我可以上传到我的项目中的服务器以及有关我在数据库中的照片存储的信息。这就是我的数据库中的记录如下所示: Id :1,路径:〜/ Upload / d8cd7f97-1da2-43f3-b43a-74e5c9f28731.JPG DispayName :9.jpg, IsMainImage :是的, FurnitureId :25。 所以这是我从服务器和数据库中删除文件的方法:
[HttpPost]
public JsonResult DeleteFile(int Id)
{
try
{
FurnitureImages furnitureImages = db.FurnitureImages.Find(Id);
if (furnitureImages == null)
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
return Json(new { Result = "Error" });
}
//Remove from database
db.FurnitureImages.Remove(furnitureImages);
db.SaveChanges();
//Delete file from the file system
var path = Server.MapPath(furnitureImages.Path);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
return Json(new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
在我看来,我将参数传递给ajax:
<script type="text/javascript">
$('.deleteItem').click(function (e) {
e.preventDefault();
var $ctrl = $(this);
if (confirm('Do you really want to delete this file?')) {
$.ajax({
url: '@Url.Action("DeleteFile")',
type: 'POST',
data: { Id: $(this).data('Id') }
}).done(function (data) {
if (data.Result == "OK") {
$ctrl.closest('li').remove();
}
else if (data.Result.Message) {
alert(data.Result.Message);
}
}).fail(function () {
alert("There is something wrong. Please try again.");
})
}
});
</script>
最后调用此函数:
@for (int i = 0; i < Model.SecondaryImages.Count; i++)
{
@Html.HiddenFor(m => m.SecondaryImages[i].Id)
@Html.HiddenFor(m => m.SecondaryImages[i].Path)
@Html.HiddenFor(m => m.SecondaryImages[i].DisplayName)
<img src="@Url.Content(Model.SecondaryImages[i].Path)" />
<a href="javascript:void(0);" data-id="@Model.SecondaryImages[i].Id" class="deleteItem">X</a>
}
此示例中的模型是ViewModel。但它不起作用,它写道“有什么不对。请再试一次”,首先条件如果不起作用,那有什么不对?感谢
答案 0 :(得分:0)
好的,问题解决了,我的Id为空,所以错误在这一行
data: { Id: $(this).data('Id') }
一定是
data: { Id: $(this).attr('data-Id') }
现在我们得到了正确的ID,图像将从服务器和文件系统中删除