Nevi
Nevi

Reputation: 328

AJAX Delete Not Working Entity Framework

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?

Upvotes: 2

Views: 503

Answers (2)

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29693

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

Upvotes: 1

Rakin
Rakin

Reputation: 1279

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>

Upvotes: 0

Related Questions