getting error while deleting record in the table – method not allowed “405 (Method Not Allowed)”

Tags: , , ,



i want to delete record using ajax call but im getting error method not allowed. 405 error.

code

HTML

 <button class="btn btn-danger" onclick="DeleteTrip(@item.TripId)">Delete</button>

JS

var DeleteTrip = function (TripId) {

        var ans = confirm("Do you want to delete item with Item Id: " + TripId);

        if (ans) {
            $.ajax({
                type: "POST",
                url: "/TripsReport/Delete/" + TripId,
                success: function () {
                    window.location.href = "/TripsReport/Index";
                }
            })
        }
    }

c# code

 [HttpPost]
        public IActionResult Delete(int id)
        {
            tripsService.DeleteTrips(id);
            return RedirectToAction("Index");
        }

Answer

I test my code,and I find HTTPDelete and HttpPost can work.

Here is a demo for HTTPDelete:

View:

<button class="btn btn-danger" onclick="DeleteTrip(1)">Delete</button>

    @section scripts{
    
        <script>
            function DeleteTrip (TripId) {
    
                var ans = confirm("Do you want to delete item with Item Id: " + TripId);
    
                if (ans) {
                    $.ajax({
                        type: "DELETE",
                        url: "/TripsReport/Delete",
                        data: {
                            id: TripId
                        },
                        success: function (data) {
                            window.location.href = "/TripsReport/Index";
                        }
                    })
                }
            }
        </script>
    }

controller:

[HttpDelete]
        public IActionResult Delete(int id)
        {
            return Ok();
        }

Result: enter image description here

Here is a demo for HTTPPost:

View:

<button class="btn btn-danger" onclick="DeleteTrip(1)">Delete</button>

    @section scripts{
    
        <script>
            function DeleteTrip (TripId) {
    
                var ans = confirm("Do you want to delete item with Item Id: " + TripId);
    
                if (ans) {
                    $.ajax({
                        type: "POST",
                        url: "/TripsReport/Delete",
                        data: {
                            id: TripId
                        },
                        success: function (data) {
                            window.location.href = "/TripsReport/Index";
                        }
                    })
                }
            }
        </script>
    }

controller:

[HttpPost]
        public IActionResult Delete(int id)
        {
            return Ok();
        }

Result: enter image description here



Source: stackoverflow