0

I use ASP.NET Core 6 MVC and Entity Framework 6.0.11 and I have trouble when deleting data from SQL Server.

When I click delete button, it makes the deletePage show 0 values, when I back to the list the data I just deleted, it does not disappear (see screenshot).

My controller:

    public IActionResult deletePackage (long ID)
    {
        ForDeletePackage = LQHVContext.Packages.Where(s => s.PackagesId == ID).FirstOrDefault();

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

        return View(ForDeletePackage);
    }

    [HttpPost]
    public IActionResult Delete(long ID)
    {                        
        Package package = new Package() { PackagesId = ID };
        LQHVContext.Packages.Attach(package);
        LQHVContext.Packages.Remove(package);

        if (LQHVContext.SaveChanges() == 1)
        {
            //redirect to package list
            return RedirectToAction("packageList", "Packages");
        }

        return View("deletePackage", package);
    }

My razor page:

<form asp-action="Delete">
    <input type="submit" value="Delete" class="btn btn-danger" /> |
    <a asp-action="listPackage">Back to List</a>
</form>

Screenshots:

My ConfirmDelete page

After I click delete btn

when I back to List, the data still there

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sar lavi
  • 3
  • 4
  • there is a verb mismatch, you have to change get to delete or vice versa in view or controller – Vivek Nuna Dec 29 '22 at 16:15
  • I have change it from [HttpDelete] to [HttpPost] and it just make the confirmDeletePage with 0 value, but when I back to the list the data was not deleted – sar lavi Dec 29 '22 at 16:23
  • Your question is unclear, by reading it we could think it's an issue related to entity framework, but the (slightly hidden) screenshots tells about an HTTP issue. I think you can't use the DELETE verb in a regular web context (that's not WebDAV or REST API for example). – AFract Dec 29 '22 at 16:46
  • I have posted an answer with picture below when I clicked the delete btn – sar lavi Dec 29 '22 at 17:02
  • It may help if you could show the details of packageList Action – Ruikai Feng Dec 30 '22 at 03:01

1 Answers1

0

I doubt HTML forms can do a DELETE HTTP operation against our API. The only two options are POST and GET

See this question as well Should PUT and DELETE be used in forms?

Tore Nestenius
  • 16,431
  • 5
  • 30
  • 40
  • Thank you so much for your answer and I have change the httpDelete into httpPost but it just make the deletePage show 0 value, when I back to the List the data I just deleted not disapear – sar lavi Dec 29 '22 at 16:26
  • can you update the code in your question? did you replace [HttpDelete] with [HttpPost] ? – Tore Nestenius Dec 29 '22 at 16:47