Reputation: 5
I am a beginner in dotnet and trying hard to be good. I tried deleting contacts from the database using ajax, javascript and json but the delete button is not working as expected, it is actually hitting the error function in the ajax call. Any help would be highly appreciated.
My controller is:
public HttpResponseMessage Delete(int id)
{
try
{
using (ContactDBEntities entities = new ContactDBEntities())
{
var entity = entities.Contacts.FirstOrDefault(e => e.ID == id);
if (entity == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Contact with Id = " + id.ToString() + " is not found to delete");
}
else
{
entities.Contacts.Remove(entity);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
and my JS is:
<input id="btnDelete" class="btn btn-danger" type="button" data-model-id="@model.Id" value="Delete Contact" />
$('#btnDelete').click(function () {
var FirstName = $('#txtFirstName').val();
var LastName = $('#txtLastName').val();
var PhoneNumber = $('#txtPhoneNumber').val();
$.ajax({
url: "/api/Contacts/",
type: "Delete",
}).done(function () {
alert("Contact Deleted")
txtFirstName.empty();
txtLastName.empty();
txtPhoneNumber.empty()
ulContact();
}).error(function () {
alert("Failed to delete contact")
});
});
Upvotes: 0
Views: 59
Reputation: 2598
Ok, lets start looking at your API.
You have a function called Delete
public HttpResponseMessage Delete(int id) {...}
Currently this is not an API funciton. An API function needs Identifiers which will tell it what type it is.
There are many types of API endpoints, but I'll just touch on 4 here: GET
, POST
, PUT
and DELETE
.
GET - Used to get info
POST - Use to send large amounts of data in the body
PUT - Same as post, but specifically for UPDATE function, like updating user info.
DELETE - To Remove Data.
Note, to tell your API what type of endpoint it is you need to add a HTTP Attribute.
[HttpDelete]
public HttpResponseMessage Delete(int id) {...}
Now your Delete Function will be able to be called by sending a DELETE request to your endpoint: /api/Contacts/
.
Lets see how it should look from your Ajax call.
$.ajax({
url: "/api/Contacts/",
type: "Delete",
})
So you named the type Delete
, which is named after your Delete function. This is incorrect. It should be one of the above mentioned types.
Coincidently there is a type called DELETE
as mentioned, but should be uppercase.
$.ajax({
url: "/api/Contacts/",
type: "DELETE",
})
This should give you a call that works.
Now I would like to clear up some missunderstandings you have about API Endpoints. The first thing is the URL. Endpoints may share a URL
. But they may not share a URL
and a TYPE
.
For example lets have a look at two sets of examples:
// URL: api/Contacts
// Type: DELETE
[HttpDelete]
public IActionResult Delete(int id) {...}
// URL: api/Contacts
// Type: GET
[HttpGet]
public IActionResult Delete2(int id) {...}
// URL: api/Contacts
// Type: POST
[HttpPost]
public IActionResult Delete3(int id) {...}
All of these API endpoints on the same controller will work. Note that the actual function name isn't important. Only the URL
and TYPE
is needed to identify the endpoint.
In the above example they all share the same URL
, but have different TYPES
. Lets look at three where they share the same TYPE
but different URLs:
// URL: api/Contacts/1
// Type: DELETE
[HttpDelete("1")]
public IActionResult Delete(int id) {...}
// URL: api/Contacts/2
// Type: DELETE
[HttpDelete("2")]
public IActionResult Delete2(int id) {...}
// URL: api/Contacts/3
// Type: DELETE
[HttpDelete("3")]
public IActionResult Delete3(int id) {...}
The calling URL in your Ajax statement will need to reference the correct url. Above we add ("SomeText")
to the [Http..]
attribute.
You can type anything for the text and it will change the url. Usefull when you have multiple functions in the same controller.
Another powerfull thing about APIs is specifying the types of Inputs. In your function Delete(int id)
you are passing the id
variable as Query Parameter
.
You probally would not have know this as the default type of input is a query parameter, but you can change where you get the variables from.
There are 3 main ones you should be aware of: [FromQuery]
, [FromRoute]
and [FromBody]
.
below I will show you have to ulitise all of them using C# & Ajax:
This is the one you are currently using, where at the end of the url you have ?
which shows what follows is Query Parameters
.
These are simply: Key=Value
. If you want multiple just seperate them with &
: Key=Value&Key2=Value2
// C#
[HttpDelete]
public IActionResult Delete([FromQuery] int id) {...}
// AJAX
$.ajax({
url: "/api/Contacts?id=4",
type: "DELETE"
})
Now this is when you get your data from your URL itself. You need to be aware that the syntax for the "{id}" needs to match the int id
as seen below.
// C#
[HttpDelete("{id}")]
public IActionResult Delete([FromRoute] int id) {...}
// AJAX
$.ajax({
url: "/api/Contacts/4",
type: "DELETE"
})
The last one is [FromBody]
, but only works if you have a POST
or PUT
Type. GET
and DELETE
do not support bodies. Very usefull when sending large objects or form data. Though for forms best to use the [FromForm]
tag which is functionally similar.
// C#
[HttpDelete]
public IActionResult Delete([FromBody] int id) {...}
// AJAX
$.ajax({
url: "/api/Contacts/",
type: "POST",
data:{
id: 4
}
})
Upvotes: 1