Jquery Ajax Post删除服务器+ asp.net上的文件mvc + c#
嗨,我一直在试图创建一个链接,删除存储在服务器上的图片,并从数据库中删除信息。我想要使用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);
}
回答:
这就像它变得愚蠢!
微妙的条件错误:
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
}
回答:
您应该将参数传递给您的控制器方法
$.ajax({ url: this.href,//check this.href in debugger
dataType: "text json",
type: "POST",
data: {Id: Id }, //pass argument here
success: function (data, textStatus) { }
});
以上是 Jquery Ajax Post删除服务器+ asp.net上的文件mvc + c# 的全部内容, 来源链接: utcz.com/qa/260747.html