2012-11-19 62 views
1

嗨,我一直在試圖創建一個鏈接,刪除存儲在服務器上的圖片,並從數據庫中刪除信息。我想要使​​用ajax發佈鏈接。我嘗試了一切,但它不起作用。Jquery Ajax Post刪除服務器+ asp.net上的文件mvc + c#

但是,它的工作原理,如果我試圖做別的事情而不是刪除 - 說更新數據庫中的字段。

你能告訴我我做錯了什麼嗎?

查看:

<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> 

JQuery的:

<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); 
    } 
+1

如何在控制器傳遞的ID屬性? –

+0

它是否從路由映射中選取它 - 它適用於我擁有的其他類似ajax文章。我正在嘗試通過Sanja的建議 – Tripping

回答

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); 
     } 

至於數據庫的一部分,我沒有保存數據庫:

public void DeletePhotoFromDb(PropertyPhotos photo) 
    { 
     db.PropertyPhotos.Remove(photo); 
     db.SaveChanges(); // Missing this line 
    } 
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) { } 
     }); 
+0

不確定,因爲我目前的方法工作,如果說我必須更改數據庫上的文件的名稱與刪除它 - 使用相同的控制器操作 – Tripping

+0

Doesn't .. ..我有把@ item.PropertyPhotosId放在a標籤的id中。並沒有什麼問題。 – Tripping

+0

@Tripping你檢查了這個.href是否正確? –