Handling HTTP Delete Method in AngularJS and C#

HTML/AngularJS Frontend

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>AngularJS HTTP DELETE Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-controller="myController">
    <h2>Delete Resource</h2>
    <form ng-submit="deleteResource()">
        <label for="resourceId">Resource ID:</label>
        <input type="text" ng-model="resourceId" required>

        <button type="submit">Delete Resource</button>
    </form>
</body>
</html>

AngularJS Frontend (JavaScript)

var app = angular.module('myApp', []);

app.controller('myController', function ($scope, $http) {
    $scope.deleteResource = function () {
        $http.delete('https://ResourceController/api/resource/' + $scope.resourceId)
            .then(function (response) {
                console.log("Resource deleted successfully.");
            })
            .catch(function (error) {
                console.error("Error deleting resource:", error);
            });
    };
});

C# Backend (Controller using ASP.NET Web API)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

public class ResourceController : ApiController
{
    private static List<Resource> resourceList = new List<Resource>
    {
        new Resource { Id = 1, Name = "Resource1" },
        new Resource { Id = 2, Name = "Resource2" },
        new Resource { Id = 3, Name = "Resource3" }
    };

    [HttpDelete]
    [Route("api/resource/{id}")]
    public IHttpActionResult DeleteResource(int id)
    {
        try
        {

            Resource resourceToDelete = resourceList.FirstOrDefault(r => r.Id == id);

            if (resourceToDelete == null)
            {

                return NotFound();
            }

            resourceList.Remove(resourceToDelete);


            return Ok(new { Message = "Resource deleted successfully." });
        }
        catch (Exception ex)
        {

            return InternalServerError(ex);
        }
    }
}

public class Resource
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Conclusion

This tutorial demonstrated the implementation of the HTTP DELETE method in an AngularJS frontend, communicating with a C# backend through ASP.NET Web API. The AngularJS controller captures user input, sends a DELETE request to the backend, and the C# controller processes the request, removing the specified resource from a simulated data store. This example provides a foundational understanding of handling resource deletions in a web application.


Similar Articles