How to delete data using Post request in Asp.Net MVC?

In this article we will understand How to delete data using Post request in Asp.Net MVC? and How to add Confirmation alert box on button click in Asp.Net MVC by Sagar Jaybhay.





Always remember if you want to delete data from the database use Post request. Never use Get request for deleting resources on a database. Because if you have to get a call to delete data from the database and any hacker or some malicious user got your Get URL then he can delete your data. Also, google try to index your page as an SEO point view so if you issue get request then it’s not good practice to delete data using Get so always use Post request to delete data.





In our application see below image we use action link to delete Employee from a database but this will issue a get request to avoid this we need to use the button for post-call and this we need to use Form control in our application so we rap our application inside form and issues a Post call for delete.









To create button control here code is below





@model IEnumerable<WebApplication1.Models.Employee>
@using WebApplication1.Models

@
ViewBag.Title = "DisplayCompleteEmployee";


<h2>Display Complete Employee</h2>

<br />
<div class="row" style="margin-left:0px !important">
@Html.ActionLink("Create Employee", "Create")
</div>
<br />
<hr />
<br />
<table class="table table-bordered table-responsive">
<thead>
<tr>
<td>Name</td>
<td>Gender</td>
<td>City</td>
<td>Email</td>
<td>Salary</td>
<td>Take Action</td>
</tr>
</thead>
<tbody>
@foreach (var emp in Model)

@Html.ActionLink("Details", "Index", new EmpID = emp.EmpID )

</tbody>

</table>








The output of the above code is shown below image









Now we need to create a Delete method in our controller and for that, we need to create a delete method in our Business class. So first create that after that we create a method in Controller.





Below is a method in Business Class





public int DeleteEmployee(int Id)

string query = "delete from employee where empid="+Id;
return this.dataAccess.ExecuteQuery(query);






Below is the method in Controller





[HttpPost]
public ActionResult Delete(string EmpID)

new BusinessLogic.Business().DeleteEmployee(Convert.ToInt32(EmpID));
return RedirectToAction("DisplayCompleteEmployee");





Now our functionality is worked as expected. But you want to add more confirmation like below image









For this, you need to use the below code for that.





@using (Html.BeginForm("Delete","Employee",new EmpID=emp.EmpID))

<input type="submit" class="btn btn-danger" value="Delete" onclick="return confirm('Are U sure for Delete EmpId=@emp.EmpID')"/>





GitHub :- https://github.com/Sagar-Jaybhay/MVC5

Comments

Popular posts from this blog

How to Start a YouTube Channel Free - Complete Guide

How Angular know which module is the startup module?

How to Start a YouTube Channel Free - Complete Guide