In the post AngularJS Ajax using $http we saw that we can perform Ajax calls to
the server in AngularJS using $http service, and we saw that $http supports
Get, Post, Put and Delete operations. In this post we shall see on how to make
a $http.delete Ajax call in
AngularJS
The following example shows how to make a $http.delete call to an Asp.Net Web API Controller method.
WebAPI Post MethodThe following example shows how to make a $http.delete call to an Asp.Net Web API Controller method.
public class PackageController : ApiController
{
PkgEntities objDBContext = new PkgEntities();
//
[HttpDelete]
public string Delete(int id)
{
try
{
Package currPackage = (from Packages in
objDBContext.Packages
where Packages.PackageId
== id
select Packages).First();
//
objDBContext.Packages.Remove(currPackage);
objDBContext.SaveChanges();
return "Package
"
+ currPackage.Name + " deleted Succesfully";
}
catch (Exception ex)
{
return "Error:
"
+ ex.Message.ToString();
}
}
}
}
AngularJS
call to WebAPI Get method
$http.delete(GetRootPath() + "Package/" + packageId)
$http.delete(GetRootPath() + "Package/" + packageId)
.then(function (results) {
//Success;
try {
//alert(results.data);
}
catch (err) {
alert(err.message);
}
}, function (results) {
//error
alert("Error:
"
+ results.data + "; "
+
results.status);
})
The $http.delete method calls the server side WebAPI Post() method with the id of the package to be deleted as the parameter. The WebAPI contoroller’s Delete method automatically receives this call and deletes the corresponding package from the Database Context and returns a success/failure message to AngularJS. The AngularJS client method receives the message and displays it to the end user.
No comments:
Post a Comment