In this article I will explain with an example, how to delete all records using
Entity Framework in ASP.Net MVC.
Database
I have made use of the following table Customers with the schema as follow.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Entity Framework Model
Once the
Entity Framework is configured and connected to the database table, the Model will look as shown below.
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
Inside the Action Method, Customer Collection is passed to the
RemoveRange method of
Entity Framework and the
SaveChanges method of
Entity Framework is called which updates the changes to the database.
Then, a success message is set to a
TempData object named “Message”.
Finally, the page is redirected to Index Action method.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult DeleteAll()
{
AjaxSamplesEntities entities = new AjaxSamplesEntities();
entities.Customers.RemoveRange(entities.Customers);
entities.SaveChanges();
TempData["Message"] = "Customer records are deleted.";
return RedirectToAction("Index");
}
}
View
HTML Markup
The View consists of HTML Form which has been created using the Html.BeginForm method with the following parameters.
asp-action – Name of the Action. In this case the name is DeleteAll.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The form consists of Submit button.
The
TempData object named Message is checked for NULL and if it is not NULL then the value of the object is displayed using
JavaScript Alert MessageBox.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("DeleteAll", "Home", FormMethod.Post))
{
<input type="submit" value="Delete All" />
}
@if (TempData["Message"] != null)
{
<script type="text/javascript">
window.onload = function () {
alert('@TempData["Message"]');
};
</script>
}
</body>
</html>
Screenshot
Downloads