1

您好我一直在尝试创建一个链接,该链接删除存储在服务器上的图片并从数据库中删除信息。我希望使用 ajax 发布链接。我已经尝试了一切,但它不起作用。

但是,如果我尝试执行除删除以外的其他操作 - 比如说更新数据库中的字段,它会起作用。

你能告诉我我做错了什么吗?

看法:

<div class="uploaded-property-pics clearfix">
    <ul>
        @foreach (var item in Model.PropertyPhotos) {
            <li>
                <img src="@Url.Content("~/PropertyImages/" + item.PropertyId + "/" + "tn_" + item.PhotoLocation + ".png")"/>
                <a href="/Property/DeletePhoto/@item.PropertyPhotosId" class="photo-delete-link">Delete</a>
            </li>
        }
    </ul>
</div>

查询:

<script>
    $('.photo-delete-link').click(function (e) {
        $.ajax({
            url: this.href,
            dataType: "text json",
            type: "POST",
            data: {},
            success: function (data, textStatus) { }
        });
        e.preventDefault();
    });
</script>

控制器:

    [HttpPost]
    [Authorize]
    public void DeletePhoto(int id)
    {
        var photo = websiteRepository.GetPhotoByPhotoId(id);
        var folder = Server.MapPath("~/PropertyImages/" + photo.PropertyId + "/");

        if (!Directory.Exists(folder))
        {
            var filePath = folder + photo.PhotoLocation + ".png";
            var thumbPath = folder + "tn_" + photo.PhotoLocation + ".png";
            websiteRepository.DeletePhotoFromServer(filePath);
            websiteRepository.DeletePhotoFromServer(thumbPath);
        }

        websiteRepository.DeletePhotoFromDb(photo);
    }

数据访问:

    public void DeletePhotoFromDb(PropertyPhotos photo)
    {
        db.PropertyPhotos.Remove(photo);
    }

    public void DeletePhotoFromServer(string filePath) 
    {
        File.Delete(filePath);
    }
4

2 回答 2

0

您应该将参数传递给您的控制器方法

$.ajax({
            url: this.href,//check this.href in debugger
            dataType: "text json",
            type: "POST",
            data: {Id: Id }, //pass argument here
            success: function (data, textStatus) { }
        });
于 2012-11-19T21:24:05.523 回答
0

这太愚蠢了!

微妙的条件错误:

if (Directory.Exists(folder)) // Note the subtle condition difference
        {
            var filePath = folder + photo.PhotoLocation + ".png";
            var thumbPath = folder + "tn_" + photo.PhotoLocation + ".png";
            websiteRepository.DeletePhotoFromServer(filePath);
            websiteRepository.DeletePhotoFromServer(thumbPath);
        }

至于 db 部分,我没有保存数据库:

public void DeletePhotoFromDb(PropertyPhotos photo)
    {
        db.PropertyPhotos.Remove(photo);
        db.SaveChanges(); // Missing this line
    }
于 2012-11-19T22:20:39.027 回答