Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi everybody, i want to delete an image after uploading, I have this for view:

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 )
    {
     <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:

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:

C#
[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;
                        // Get the userprofile
                        user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));

                        // Update fields
                        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);

               

                // delete file using path 
               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:

C#
@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:


JavaScript
//Delete photo:
            $('.photo-delete-link').click(function (e) {
                $.ajax({
                    url: "/Account/DeleteFiles/",
                    dataType: "text json",
                    type: "POST",
                    data: {},
                    success: function (data, textStatus) { }
                });
                e.preventDefault();
            });


            //End Delete photo


and controller action:

C#
[HttpPost]
        //[ValidateAntiForgeryToken]
        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);

                // you now have access to the information of the file, including path, name, etc

                // delete file using your filepath (path + filename)
               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:


JavaScript
//Delete photo:
        $('.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();
        });


        //End Delete photo


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:


JavaScript
//Delete photo:
    $('.photo-delete-link').click(function (e) {
        $.ajax({
            type: "POST",
            url: "/Account/DeleteFiles/",
            contentType: false,
            processData: false,

            data: data,
            success: function () { }
        });
        e.preventDefault();
    });


    //End Delete photo


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:

JavaScript
//Delete photo:
            $('.photo-delete-link').click(function (e) {
                $.ajax({
                    url: "/Account/DeleteFiles/",
                    dataType: "text json",
                    type: "POST",
                    data: {},
                    success: function (data, textStatus) { }
                });
                e.preventDefault();
            });


            //End Delete photo


the action method will be triggered, but then:

C#
foreach (var id in files)
files is null

oke,

I have it now like this:

JavaScript
$('.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:

C#
<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 />
           }


//This is for deleting files. SO you can select one and delete:

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

JavaScript
//Delete photo:
            $('.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:


C#
<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:

JavaScript
//Delete photo:
          $('.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:

JavaScript
$('.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 :(
Posted
Updated 25-Oct-14 9:45am
v11
Comments
Sinisa Hajnal 24-Oct-14 8:34am    
And? Which of the variables isn't set? Set breakpoint(s), see what is null and go to town.
[no name] 24-Oct-14 8:55am    
oke, thank you for you reply, I changed this:

<input type="checkbox" name="files" value="@item.ImagePath" /> but now if I select and delete nothing happens

1 solution

Please check for the files that you are sending from client side to the Server side. Debug and chck i think this error is coming up because the files is null and without null checking you are trying to get files.ComtentLength. So null's property cannot be found that gives Null Exception.
The files are not getting sent to the server Action on post.
C#
$.ajax({        
        type: "POST",
        url:"Your URL",
        contentType: false,
        processData: false,
        data: data,
        success: function() {
            // your success code goes here...
        }

Please try this in the ajax call, this might work out.
Please debug and post back your queries if any in comments.
Thanks
:)
 
Share this answer
 
v2
Comments
[no name] 25-Oct-14 12:17pm    
See above, I changed my post
[no name] 25-Oct-14 13:01pm    
Thank you, I have updated my post
[no name] 25-Oct-14 13:03pm    
But for this the URL should be for delete right??
Check the url and debug if the files are going to the action or not.
[no name] 25-Oct-14 13:25pm    
I have updated my post
[no name] 25-Oct-14 13:33pm    
that means the files are not going to the action. Could you make the data in ajax as
data:$("#formId").serialize()
Hope this works. Please try.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900