public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
CustomersEntities entities = new CustomersEntities();
List<Customer> customers = entities.Customers.ToList();
return View(customers.ToList());
}
[HttpPost]
public ActionResult DeleteCustomer(int customerId)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer customer = (from c in entities.Customers
where c.CustomerId == customerId
select c).FirstOrDefault();
entities.Customers.Remove(customer);
entities.SaveChanges();
}
return new EmptyResult();
}
}
@model IEnumerable<Customer>
@{
Layout = null;
WebGrid webGrid = new WebGrid(source: Model, canPage: true, canSort: false);
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
.Grid {
border: 1px solid #ccc;
border-collapse: collapse;
}
.Grid th {
background-color: #F7F7F7;
font-weight: bold;
}
.Grid th, .Grid td {
padding: 5px;
width: 110px;
border: 1px solid #ccc;
}
.Grid, .Grid table td {
border: 0px solid #ccc;
}
.Grid th a, .Grid th a:visited {
color: #333;
}
</style>
</head>
<body>
@webGrid.GetHtml(
htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
columns: webGrid.Columns(
webGrid.Column(header: "Customer Id", format: @<span class="label">@item.CustomerId</span>, style: "CustomerId" ),
webGrid.Column(header: "Name", format: @<span><span class="label">@item.Name</span>
<input class="text" type="text" value="@item.Name" style="display:none"/></span>, style: "Name"),
webGrid.Column(header: "Country", format: @<span><span class="label">@item.Country</span>
<input class="text" type="text" value="@item.Country" style="display:none"/></span>, style: "Country"),
webGrid.Column(format:@<span class="link">
<a class="Delete" href="javascript:;">Delete</a>
</span> )))
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
//Delete event handler.
$("body").on("click", "#WebGrid TBODY .Delete", function () {
if (confirm("Do you want to delete this row?")) {
var row = $(this).closest("tr");
var customerId = row.find(".label").html();
$.ajax({
type: "POST",
url: "/Home/DeleteCustomer",
data: '{customerId: ' + customerId + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if ($("#WebGrid TBODY tr").length == 1) {
row.find(".label").html("");
row.find(".text").val("");
row.find(".link").hide();
} else {
row.remove();
}
}
});
}
});
</script>
</body>
</html>