Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

c# - How to delete rows from table when clicking button

I'm wondering how I can delete all rows from my Alerts table in the database. I'm using ASP.NET Core in combination with Entity Framework. When I click the delete button right now I'll get an Error 404 (not found)

Any help would be greatly appreciated!

Controller

private readonly FrontlineDbContext _dbContext;

public class AlertsController : Controller{

public AlertsController( FrontlineDbContext dbContext)
{
    
    _dbContext = dbContext;
} 

[HttpPost]
[Authorize(Roles = "Admin")]
public void Delete()
{
    var alertsList = _dbContext.Alerts.ToList();
    _dbContext.Alerts.RemoveRange(alertsList);

    _dbContext.SaveChanges();

    //displays a success message after updating, as stated in the Shared>_Layout
    TempData["message"] = $"Alerts have been deleted";
}
}

AlertsView

<h1>Alerts Overview</h1>

<a asp-action="Delete"> Delete Alerts</a>
question from:https://stackoverflow.com/questions/65910991/how-to-delete-rows-from-table-when-clicking-button

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your view code is generating an GET request which is not reaching the Delete action method, because it is marked with [HttpPost] attribute.

To generate a POST request, and reach your Delete method, modify your view code as -

<form asp-action="Delete">
    <input type="submit" value="Delete" class="btn btn-link"/>
</form>

Also, replace [HttpPost] with [HttpPost, ActionName("Delete")] on the action method, just to be sure.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...