Hi rajeesh,
Check the example.
Model
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
Repository
public class Repository
{
public bool Insert(List<Customer> customers)
{
foreach (Customer customer in customers)
{
int id = customer.Id;
string name = customer.Name;
string country = customer.Country;
// Insert in Customer table and return inserted customerid.
}
return true;
}
}
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public ActionResult Insert(List<Customer> customers)
{
Repository ob = new Repository();
if (ob.Insert(customers))
{
ViewBag.Message = "Saved Successfully";
}
return View("Index");
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th style="width:150px">Name</th>
<th style="width:150px">Country</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<td><input type="text" id="txtName" /></td>
<td><input type="text" id="txtCountry" /></td>
<td><input type="button" id="btnAdd" value="Add" /></td>
</tr>
</tfoot>
</table><br />
<input type="button" id="btnSave" value="Save" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("body").on("click", "#btnAdd", function () {
var txtName = $("#txtName");
var txtCountry = $("#txtCountry");
var tBody = $("#tblCustomers > TBODY")[0];
var row = tBody.insertRow(-1);
var cell = $(row.insertCell(-1));
cell.html(txtName.val());
cell = $(row.insertCell(-1));
cell.html(txtCountry.val());
cell = $(row.insertCell(-1));
var btnRemove = $("<input />");
btnRemove.attr("type", "button");
btnRemove.attr("onclick", "Remove(this);");
btnRemove.val("Remove");
cell.append(btnRemove);
txtName.val("");
txtCountry.val("");
});
function Remove(button) {
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
if (confirm("Do you want to delete: " + name)) {
var table = $("#tblCustomers")[0];
table.deleteRow(row[0].rowIndex);
}
};
$("body").on("click", "#btnSave", function () {
var customers = new Array();
$("#tblCustomers TBODY TR").each(function () {
var row = $(this);
var customer = {};
customer.Name = row.find("TD").eq(0).html();
customer.Country = row.find("TD").eq(1).html();
customers.push(customer);
});
$.ajax({
type: "POST",
url: "/Home/Insert",
data: JSON.stringify(customers),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
</script>
</body>
</html>