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?

Nevi
  • 328
  • 2
  • 8
  • 18
  • Whats not working? What errors are you getting? Are you hitting the controller method? –  Oct 07 '15 at 03:25
  • im getting no error and also no response from controller i set a breakpoint – Nevi Oct 07 '15 at 03:27
  • 1
    Check your browser console for errors (and why are you returning `null`?) –  Oct 07 '15 at 03:29
  • @StephenMuecke what should i return? the method has no view and i dont want to use RedirectToAction – Nevi Oct 07 '15 at 03:33
  • the error is deletefunction is undefined – Nevi Oct 07 '15 at 03:34
  • Keep your delete function in `` section and try once.. – Guruprasad J Rao Oct 07 '15 at 03:35
  • Not a requirement, but try to return `Json` data from your `ActionResult` – Guruprasad J Rao Oct 07 '15 at 03:37
  • @GuruprasadRao did that no avail. – Nevi Oct 07 '15 at 03:37
  • 1
    Rather than polluting your markup with behavior, use unobtrusive javascript - `` and in the script use `$('.delete').click(function() { var photoid = $(this).data('id'); ...` –  Oct 07 '15 at 03:38
  • again you are getting same error? `deletefunction` is undefined ? Do not keep it inside `document.ready` plus better if you opt @StephenMuecke's suggestion.. – Guruprasad J Rao Oct 07 '15 at 03:38
  • @GuruprasadRao should i use return return Json(new { photoid = photoid}); – Nevi Oct 07 '15 at 03:39
  • No no.. `return Json(new {message="true"},JsonRequestBehavior.AllowGet)` or `false` based on the success and failure.. – Guruprasad J Rao Oct 07 '15 at 03:40
  • @Nevi, Refer [this question/answer](http://stackoverflow.com/questions/18504253/javascript-function-inside-document-ready) for why you current implementation will not work –  Oct 07 '15 at 03:40
  • contentType: "application/json; charset=utf-8", dataType: "json", – Rakin Oct 07 '15 at 03:43
  • @StephenMuecke i think i made it work, now its deleting the photo but it seems i need to hit F5 to see if the photo is deleted – Nevi Oct 07 '15 at 03:51
  • Do you mean the photo is actually displayed on the page? If so, then you need to remove the element from the DOM in the success callback (which is also why you should be returning a value indicating success or otherwise - e.g. `return Json(true);` and then `success: function (result) { if (result) { $(yourPhoto).remove(); }` –  Oct 07 '15 at 03:53
  • yes @StephenMuecke how do i do that? – Nevi Oct 07 '15 at 03:55
  • @Nevi use this `` and use `$('#'+photoid+'').remove()` to remove it – J Santosh Oct 07 '15 at 04:29
  • Write `function deletefunction(photoid) { //your code }` outside `$(document).ready(function () { \\your other code });`. – Kausha Mehta Oct 07 '15 at 05:13

2 Answers2

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()
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
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>
Rakin
  • 1,271
  • 14
  • 30
  • You need to remove `contentType: "application/json; charset=utf-8",` or this will not work. Either that or you need to stringify the data. –  Oct 07 '15 at 03:47