In this Video, I am going to discuss Deleting Database Records in ASP.NET MVC Application. Please read our previous Video before proceeding to this Video where we discussed Model Binding using Interface in ASP.NET MVC Application. We are also going to work with the same example that we worked on in our previous Video. As part of this Video, we are going to discuss the following pointers.
How to Delete Database Records in ASP.NET MVC?. The Complete ASP.NET MVC Developer Course 2023 [Videos].
discuss the following pointers.
Deleting Database Records using Get Request:
Lets first understand how to delete database records in ASP.NET MVC Application using a GET request and then we will discuss why it is bad to do so.
Step1: Create a stored procedure to delete employee data by “ID”
Step2: Add the following DeleteEmployee() method to the “EmployeeBusinessLayer.cs” file in the “BusinessLayer” project. This method calls the stored procedure “spDeleteEmployee” that we just created.
Step3: Add the following “DELETE” action method to “EmployeeController”.
Run the application and navigate to the “Index” action. Click the “Delete” link. This issues the “GET” request to the following URL and deletes the record.
Deleting database records using a GET request opens a security hole and is not recommended by Microsoft. Just imagine what can happen if there is an image tag in a malicious email as shown below. The moment we open the email the image tries to load and issues a GET request which would delete the data.
<img src=”http://localhost/MVC_DEMO/Employee/Delete/2″ />
Also when search engines index our page they issue a GET request which would delete the data. In general, GET requests should be free of any side effects meaning they should not change the state. Deletes should always be performed using a POST request.
Deleting Database Records using the POST Request in ASP.NET MVC Application:
Step1: Mark the “Delete” action method in the “Employee” controller with the [HttpPost] attribute. With this change, the “Delete” method will no longer respond to the “GET” request. At this point, if we run the application and click on the “Delete” link on the “Index” view we get an error stating – “The resource cannot be found“.
Step2: Modifying the “Index.cshtml”
Notice that we are using “Html.BeginForm()” HTML helper to generate a form tag.
Step3: To include client-side confirmation before the data can be deleted add the “onclick” attribute to the “Delete” button as shown below.
<input type=”submit” value=”Delete” onclick=”return confirm(Are you sure you want to delete record with ID = @item.ID);” />
Thats it run the application and see everything is working as expected.