0

I want to delete a object from my database using ASP.NET MVC. I have connected to the database with Entity Framework. I have made this code for my controller named Delete.

// DELETE-POST
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(int? id)
{
    var obj = _db.Project.Find(id);

    if(obj == null)
    {
        return NotFound();
    }

    _db.Project.Remove(obj);
    _db.SaveChanges();

    return RedirectToAction("Index");
}

Then I created a button with a link to my controller

<a asp-action="Delete" class="btn btn-danger btn-lg text-white w-30">Delete</a>

I had expect that my object should disappear. But I get an issue when I press the button. It only returns a blank site with a message that the site does not work.

Does anyone have any ideas why?

2 Answers 2

2

You have to add Id to your ancor tag. Try to use this:

<a asp-controller="...Controller"   asp-action="Delete" 
       asp-route-id="@Model.Id" class="btn btn-danger btn-lg text-white w-30">
Delete</a>
Sign up to request clarification or add additional context in comments.

Comments

0

You need to pass id from view.

<a asp-action="Delete" asp-route-id="@Model.Id" class="btn btn-danger btn-lg text-white w-30">Delete</a>

1 Comment

Solved the problem! Thank you so much !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.