public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
CustomersEntities entities = new CustomersEntities();
List<Customer> customers = entities.Customers.ToList();
// If no records then add a dummy row.
if (customers.Count == 0)
{
customers.Add(new Customer());
}
return View(customers);
}
[HttpPost]
public JsonResult InsertCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
entities.Customers.Add(customer);
entities.SaveChanges();
return Json(customer);
}
}
}
@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: 150px;
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("Name", "Name"),
webGrid.Column("Country", "Country")))
<br/>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 150px">
Name:<br/>
<input type="text" id="txtName" style="width:140px"/>
</td>
<td style="width: 150px">
Country:<br/>
<input type="text" id="txtCountry" style="width:140px"/>
</td>
<td style="width: 100px">
<br/>
<input type="button" id="btnAdd" value="Add"/>
</td>
</tr>
</table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAdd").click(function () {
//Reference the WebGrid.
var webGrid = $("#WebGrid");
//Reference the first row.
var row = webGrid.find("tr").eq(1);
//Check if row is dummy, if yes then remove.
if ($.trim(row.find("td").eq(0).html()) == "") {
row.remove();
}
//Clone the reference first row.
row = row.clone(true);
//Reference the Name TextBox.
var txtName = $("#txtName");
//Reference the Country TextBox.
var txtCountry = $("#txtCountry");
//Send the records to server for saving to database.
$.ajax({
type: "POST",
url: "/Home/InsertCustomer",
data: '{name: "' + txtName.val() + '", country: "' + txtCountry.val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
//Add the Name value to first cell.
SetValue(row, 0, txtName);
//Add the Country value to second cell.
SetValue(row, 1, txtCountry);
//Add the row to the WebGrid.
webGrid.append(row);
}
});
});
function SetValue(row, index, textbox) {
//Reference the Cell and set the value.
row.find("td").eq(index).html(textbox.val());
//Clear the TextBox.
textbox.val("");
}
});
</script>
</body>
</html>