Emiel Emiel - 1 month ago 8
ASP.NET (C#) Question

jquery to mvc methode

I would like to delete a db-entry using jQuery and a mvc-actionmethode. But I can't seem to get the deletemethode working..

Index.cshtml

code controller

// DELETE: api/Categories/5
[ResponseType(typeof(Category))]
public IHttpActionResult DeleteCategory(int id)
{
Category category = db.Categories.Find(id);
if (category == null)
{
return NotFound();
}

db.Categories.Remove(category);
db.SaveChanges();

return Ok(category);
}

Answer

Let's get started. I'm assuming that you are using an ApiController.

If you use a controller called Categories, then it's a good practice to use the name of your method the verb it represents. If you want to send a DELETE: api/categories/id, then you should have your method:

[ResponseType(typeof(Category))]
public IHttpActionResult Delete(int id)
{
    Category category = db.Categories.Find(id);
    if (category == null)
    {
        return NotFound();
    }

    db.Categories.Remove(category);
    db.SaveChanges();

    return Ok(category);
}

If you really want to call it DeleteCategory, then you should say what http verb it represents:

[HttpDelete]
[ResponseType(typeof(Category))]
public IHttpActionResult DeleteCategory(int id)
{
    Category category = db.Categories.Find(id);
    if (category == null)
    {
        return NotFound();
    }

    db.Categories.Remove(category);
    db.SaveChanges();

    return Ok(category);
}

But the main reason it's not working is because your function is not doing anything but calling an alert

function DeleteCategory(item) 
{
    alert(item);
}

ps: Don't use curly braces on the next line while you are working with javascript. You can fall into problems with javascript's automatic semicolon insertion. Always do:

function DeleteCategory(item) {
    alert(item);
}
Comments