Hi everybody, i want to delete an image after uploading, I have this for view:
<div id="tabs-3">
@using (Html.BeginForm("UploadMorePhotos", "Account", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-field">
<p>Select pictures:</p>
<div class="upload-container">
<div class="upload">
<input type="file" name="files" value="" multiple="multiple" id="file1" />
<img src="@Url.Content("~/images/deleteButton.png")" alt="Remove picture." />
</div>
</div>
</div>
<div class="form-field">
<input type="submit" value="Upload" />
</div>
<br />
foreach (var item in Model.LolaBikePhotos )
{
<img src="~/Images/profile/@item.ImagePath" alt="" height=150 width=200 />
using (Html.BeginForm("DeleteFiles"))
{
<table>
<tr>
<td></td>
<td>File Name</td>
</tr>
<tr>
<td>
<input type="checkbox" name="FileIds" value="@item.ImagePath" />
</td>
<td>@item.ImagePath</td>
</tr>
</table>
<input type="submit" value="Delete" />
}
}
}
<br />
</div>
javascript:
var currentImage = 1;
$("body").on("change", "input[name='files']", function () {
var pathToRemoveIcon = "@Url.Content("~/Images/deleteButton.png")";
currentImage = currentImage + 1;
var htmlToAppend = '<div class="upload"><input type="file" name="files" id="file' + currentImage + '" /><img src="' + pathToRemoveIcon + '" alt="Remove picture." /></div>';
$('.upload-container').append(htmlToAppend);
}).on("click", ".upload img", function () {
if ($(this).parent().siblings().length > 0) {
$(this).parent().remove();
}
});
and this are my action methods:
[HttpPost]
public ActionResult UploadMorePhotos(UserProfile user, IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/profile" + @"\" + fileName.Replace('+', '_')));
file.SaveAs(path);
if (ModelState.IsValid)
{
string username = User.Identity.Name;
user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
user.Image = new byte[file.ContentLength];
file.InputStream.Read(user.Image, 0, file.ContentLength);
user.ImageMimeType = file.ContentType;
db.Entry(user).State = EntityState.Modified;
if (user != null)
{
var lolaphoto = new LolaBikePhoto
{
UserProfileID = user.Id
};
db.lolabikerPhotos.Add(lolaphoto);
lolaphoto.ImagePath = fileName;
}
}
db.SaveChanges();
}
}
return Redirect(Url.Action("Edit", "Account") + "#tabs-3");
}
[HttpPost]
public ActionResult DeleteFiles(IEnumerable<HttpPostedFileBase> files)
{
foreach (var id in files)
{
var fileName = Path.GetFileName(id.FileName);
var path = Path.Combine(Server.MapPath("~/Images/profile" + @"\" + fileName.Replace('+', '_')));
var file = db.lolabikerPhotos.Find(id);
System.IO.File.Delete(path);
}
return View();
}
but if I select image and press delete I get this error:
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 397: foreach (var file in files)
Line 398: {
Line 399: if (file.ContentLength > 0)
Line 400: {
Line 401: var fileName = Path.GetFileName(file.FileName);
Source File: g:\Mijn Documents\My Web Sites\Lolabikes - Copy\C#\ContosoUniversity\Controllers\AccountController.cs Line: 399
Thank you
oke, I have it now like this:
@foreach (var item in Model.LolaBikePhotos )
{
<table>
<tr>
<td>
<img src="/Images/profile/@item.ImagePath" alt="" height=150 width=200 />
<a href="/Images/profile/@item.PhotoID" class="photo-delete-link">Delete</a>
@*<input type="checkbox" name="files" value="@item.ImagePath" />*@
</td>
@*<td>@item.ImagePath</td>*@
</tr>
</table>
<input type="submit" class="photo-delete-link" value="Delete" />
}
and ajax call:
$('.photo-delete-link').click(function (e) {
$.ajax({
url: "/Account/DeleteFiles/",
dataType: "text json",
type: "POST",
data: {},
success: function (data, textStatus) { }
});
e.preventDefault();
});
and controller action:
[HttpPost]
public ActionResult DeleteFiles(IEnumerable<HttpPostedFileBase> files)
{
foreach (var id in files)
{
var fileName = Path.GetFileName(id.FileName);
var path = Path.Combine(Server.MapPath("~/Images/profile" + @"\" + fileName.Replace('+', '_')));
var file = db.lolabikerPhotos.Find(id);
System.IO.File.Delete(path);
db.SaveChanges();
}
return Redirect(Url.Action("Edit", "Account") + "#tabs-3");
}
but it hits now the action method, but files is null. And yes, I select a photo, so there is photo in the file system and the name I see in the correct database table.
Thank you
ok, I have it now like this:
$('.photo-delete-link').click(function (e) {
$.ajax({
type: "POST",
url: "/Account/DeleteFiles/",
contentType: false,
processData: false,
dataType: "text json",
data: data,
success: function (data, textStatus) { }
});
e.preventDefault();
});
but then I get this:
<a href="http://localhost:41787/Images/profile/97">http://localhost:41787/Images/profile/97</a>[<a href="http://localhost:41787/Images/profile/97" target="_blank" title="New Window">^</a>]
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Images/profile/97
But 97 is the id of:PhotoID 97
But the action method: DeleteFiles is not hit now when I press on Delete
if I do this:
$('.photo-delete-link').click(function (e) {
$.ajax({
type: "POST",
url: "/Account/DeleteFiles/",
contentType: false,
processData: false,
data: data,
success: function () { }
});
e.preventDefault();
});
I get this:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Images/profile/97
And the Action method is not hitting
if I do this:
$('.photo-delete-link').click(function (e) {
$.ajax({
url: "/Account/DeleteFiles/",
dataType: "text json",
type: "POST",
data: {},
success: function (data, textStatus) { }
});
e.preventDefault();
});
the action method will be triggered, but then:
foreach (var id in files)
files is null
oke,
I have it now like this:
$('.photo-delete-link').click(function (e) {
$.ajax({
type: "POST",
url: "/Account/DeleteFiles/",
contentType: false,
processData: false,
data:$("#formId").serialize() ,
success: function () { }
});
e.preventDefault();
});
and the action method is indeed been triggered.
but then it still says: files is null. How can it be null? I select the photo and press delete
I have it now like this:
<pre lang="c#"> <div id="tabs-3">
@using (Html.BeginForm("UploadMorePhotos", "Account", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-field">
<p>Select pictures:</p>
<div class="upload-container">
<div class="upload">
<input type="file" name="files" value="" multiple="multiple" id="file1" />
<img src="@Url.Content("~/images/deleteButton.png")" alt="Remove picture." />
</div>
</div>
</div>
<div class="form-field">
<input type="submit" value="Upload" />
</div>
<br />
}
@foreach (var item in Model.LolaBikePhotos )
{
<table>
<tr>
<td>
<img src="/Images/profile/@item.ImagePath" alt="" height=150 width=200 />
<a href="/Images/profile/@item" class="photo-delete-link">Delete</a>
@*<input type="checkbox" name="files" value="@item.ImagePath" />*@
</td>
@*<td>@item.ImagePath</td>*@
</tr>
</table>
<input type="submit" value="Delete" />
}
<br />
</div>
javascript:
$('.photo-delete-link').click(function (e) {
$.ajax({
type: "POST",
url: "/Account/DeleteFiles/",
contentType: false,
processData: false,
data: $("#id").serialize(),
success: function () { }
});
e.preventDefault();
});
But what is my formid? Thank you
oke,
I have it now like this:
<div id="tabs-3">
@using (Html.BeginForm("UploadMorePhotos", "Account", FormMethod.Post, new { enctype = "multipart/form-data", id = "formSubmit" }))
{
@Html.AntiForgeryToken()
<div class="form-field">
<p>Select pictures:</p>
<div class="upload-container">
<div class="upload">
<input type="file" name="files" value="" multiple="multiple" id="file1" />
<img src="@Url.Content("~/images/deleteButton.png")" alt="Remove picture." />
</div>
</div>
</div>
<div class="form-field">
<input type="submit" value="Upload" />
</div>
<br />
foreach (var item in Model.LolaBikePhotos)
{
<table>
<tr>
<td>
<img src="/Images/profile/@item.ImagePath" alt="" height=150 width=200 />
<a href="/Images/profile/@item.PhotoID" class="photo-delete-link">Delete</a>
@*<input type="checkbox" name="files" value="@item.ImagePath" />*@
</td>
@*<td>@item.ImagePath</td>*@
</tr>
</table>
<input type="submit" value="Delete" />
}
}
and javascript:
$('.photo-delete-link').click(function (e) {
$.ajax({
type: "POST",
url: "/Account/DeleteFiles/",
contentType: false,
processData: false,
data: $("#formSubmit").serialize(),
success: function () { }
});
e.preventDefault();
});
the action method has been triggered, but still files null?
THis:
$('.photo-delete-link').click(function (e) {
$.ajax({
type: "POST",
url: "/Account/DeleteFiles/",
contentType: false,
processData: false,
data: $("#formSubmit").serialize(),
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("What you do??");
}
});
e.preventDefault();
});
Still get the error message :(