2

I wonder why its not working, here is the code

View

<input type="button" value="Delete" onclick="deletefunction(@item.PhotoId)"/>

Controller

[HttpPost]
public ActionResult Delete(int photoid)
{
    var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
    if (imgDelete == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    db.Photos.Remove(imgDelete);
    db.SaveChanges();
    System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
    System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
    return null;
}

JQUERY/AJAX

<script type="text/javascript">
    $(document).ready(function () {
        function deletefunction(photoid) {
            $.ajax({
                url: '@Url.Action("Delete")',
                type: 'POST',
                data: { photoid: photoid },
                success: function (result) {
                    alert: ("Success")
                },
                error: {
                    alert: ("Error")
                }
            });
        };
    });
</script>

im new to jquery and ajax, im trying to delete the photo without refreshing the page, am i in the correct path?

19
  • Whats not working? What errors are you getting? Are you hitting the controller method? Commented Oct 7, 2015 at 3:25
  • im getting no error and also no response from controller i set a breakpoint Commented Oct 7, 2015 at 3:27
  • 1
    Check your browser console for errors (and why are you returning null?) Commented Oct 7, 2015 at 3:29
  • @StephenMuecke what should i return? the method has no view and i dont want to use RedirectToAction Commented Oct 7, 2015 at 3:33
  • 1
    Rather than polluting your markup with behavior, use unobtrusive javascript - <input type="button" value="Delete" class="delete" data-id="@item.PhotoId"> and in the script use $('.delete').click(function() { var photoid = $(this).data('id'); ... Commented Oct 7, 2015 at 3:38

2 Answers 2

1

I would suggest to attach click event to your button instead of writing javascript in markup. Consider the below markup:

<input type="button" class="delete" value="Delete" data-picid="@item.photoId"/>

Now attach a click event to .delete as below:

$('.delete').on('click',function(){
    var photoId=$(this).attr('data-picid');//gets your photoid
    $.ajax({
          url: '@Url.Action("Delete")',
          type: 'POST',
          data: JSON.stringify({ photoid: photoId }),
          contentType: "application/json; charset=utf-8", 
          dataType: "json", //return type you are expecting from server
          success: function (result) {
              //access message from server as result.message and display proper message to user
              alert: ("Success")
          },
          error: {
              alert: ("Error")
          }
    });
});

Your Controller then:

[HttpPost]
public ActionResult Delete(int photoid)
{
    var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
    if (imgDelete == null)
    {
        return Json(new{ message=false},JsonRequestBehavior.AllowGet);//return false in message variable
    }
    db.Photos.Remove(imgDelete);
    db.SaveChanges();
    System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
    System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
    return Json(new{ message=false},JsonRequestBehavior.AllowGet); //return true if everything is fine
}

Once photo is deleted based on the success or failure your can do it as below in success of ajax, but before that store a reference to yourbutton` as below:

$('.delete').on('click',function(){
    var photoId=$(this).attr('data-picid');//gets your photoid
    var $this=$(this);
    $.ajax({
          url: '@Url.Action("Delete")',
          type: 'POST',
          data: JSON.stringify({ photoid: photoId }),
          contentType: "application/json; charset=utf-8", 
          dataType: "json", //return type you are expecting from server
          success: function (result) {
              if(result.message)
              { 
                   $this.closest('yourrootparentselector').remove();
                   //here yourrootparentselector will be the element which holds all 
                   //your photo and delete button too
              }
          },
          error: {
              alert: ("Error")
          }
    });
});

UPDATE

Based on your given mark up you I suggest to add one more root parent for your each image and delete button as below:

<div style="margin-top: 17px;">
   <div id="links"> 
        @foreach (var item in Model.Content) 
        { 
            <div class="rootparent"> <!--rootparent here, you can give any classname-->
                 <a href="@item.ImagePath" title="@item.Description" data-gallery> 
                     <img src="@item.ThumbPath" alt="@item.Description" class="img-rounded" style="margin-bottom:7px;" /> 
                  </a> 
                  <input type="button" class="delete" value="Delete" data-picid="@item.PhotoId" /> 
            </div>

         } 
    </div>
</div>

Now you can write this in success

$this.closest('.rootparent').remove()
Sign up to request clarification or add additional context in comments.

3 Comments

this works, how can i remove the element photo to DOM after successfully deleting
<div style="margin-top: 17px;"> <div id="links"> @foreach (var item in Model.Content) { <a href="@item.ImagePath" title="@item.Description" data-gallery> <img src="@item.ThumbPath" alt="@item.Description" class="img-rounded" style="margin-bottom:7px;" /> </a> <input type="button" class="delete" value="Delete" data-picid="@item.PhotoId" /> } </div> </div>
is there such this as $this.closest('.rootparent').remove().where(photoid = photoid)
0

Try this.

<script type="text/javascript">
        $(document).ready(function () {

        });
     function deletefunction(photoid) {
                $.ajax({
                    url: '@Url.Action("Delete")',
                    type: 'POST',    
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: { photoid: photoid },
                    success: function (result) {
                        alert: ("Success")
                    },
                    error: {
                        alert: ("Error")
                    }
                });
            }
    </script>

1 Comment

You need to remove contentType: "application/json; charset=utf-8", or this will not work. Either that or you need to stringify the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.