In this article I will explain with an example, how to insert (save) multiple rows (records) to database using Entity Framework in ASP.Net.
 
 

Database

I have made use of the following table Customers with the schema as follow.
Insert (Save) Multiple rows (records) to database using Entity Framework in ASP.Net
 
Note: You can download the database table SQL by clicking the download link below.
            Download SQL file
 
 

Configuring and connecting Entity Framework to database

First, you need to configure and connect Entity Framework to database.
Note: For more details on how to configure and connect Entity Framework to database, please refer my article Configure Entity Framework Step By Step in ASP.Net.
 
 

HTML Markup

The HTML Markup Consists of following Controls:
TextBox – For capturing Name, Country to be inserted.
Button – For Add, Remove, Save the records.
 
The HTML Table consists of the following elements:
1. THEAD – The Header row.
2. TBODY – Left empty for dynamically adding (inserting) rows to the HTML Table.
3. TFOOT – The footer row, consisting of two TextBoxes and a Button for dynamically adding (inserting) rows to the HTML Table.

Populate HTML Table

Inside the jQuery document ready event handler, a jQuery AJAX is made to the WebMethod i.e. GetCutomers.
Then inside the Success event handler, a loop is executed for each Customers return from the WebMethod.
Finally, the item of the HTML Table Row is cloned and the columns values are set to their respective fields.
 

Adding a new row

The Add button in the Footer row of the HTML Table is assigned with a jQuery clicked event handler.
Then inside the event handler value of the Name and Country are fetched from their respective TextBoxes and are added as a new row to the HTML Table.
 

Inserting multiple rows to database using AJAX

The Save All button is assigned with a jQuery clicked event handler.
Inside the event handler a loop is executed over all rows of the HTML Table Body and a JSON array of Customer objects is generated.
Then, the JSON array is then sent to the WebMethod using jQuery AJAX function and once the response is received it is displayed using JavaScript Alert Message Box.
 

Removing a row

The Remove button in any row of the HTML Table is assigned with a jQuery clicked, then row and name is referenced.
Then check is performed and confirmation dialog box is displayed if user clicks on Ok button then, it gets the table reference and delete the row using its index.
Note: For more details on adding and remove rows from HTML Table using jQuery, please refer my article Add (Insert) / Remove (Delete) Table Rows dynamically using jQuery.
 
<table id="tblCustomers"> 
    <thead>
        <tr>
            <th>Name</th>
            <th>Country</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td></td>
            <td><asp:Button runat="server" Text="Remove" OnClientClick="return Remove(this)" /></td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td
            <td><asp:TextBox ID="txtCountry" runat="server"></asp:TextBox></td
            <td><asp:Button ID="btnAdd" runat="server" Text="Add" /></td
        </tr>
    </tfoot>
</table>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save All"  /> 
 
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $.ajax({
             type: "POST",
             url: "Default.aspx/GetCustomers",
             data: '{}',
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: function (response) {
                var row = $("#tblCustomers tbody tr:last-child").clone(true);
                $("#tblCustomers tbody tr").not($("#tblCustomers tbody tr:first-child")).remove();
                $.each(response.dfunction (index, customer) {
                    $("td", row).eq(0).html(customer.Name);
                    $("td", row).eq(1).html(customer.Country);
                    $("#tblCustomers tbody").append(row);
                    row = $("#tblCustomers tbody tr:last-child").clone(true);
                });
 
                if ($("#tblCustomers tr").length > 2) {
                    $("#tblCustomers tr:eq(1)").remove();
                }
             },
             error: function (response) {
                alert(response.responseText);
            }
        });
 
        $("[id*=btnAdd]").on("click"function () {
            //Reference the Name and Country TextBoxes.
            var txtName = $("[id*= txtName]");
            var txtCountry = $("[id*= txtCountry]");
 
            //Get the reference of the Table's TBODY element.
            var tBody = $("#tblCustomers > TBODY")[0];
 
            //Add Row.
            var row = tBody.insertRow(-1);
 
            //Add Name cell.
            var cell = $(row.insertCell(-1));
            cell.html(txtName.val());
 
            //Add Country cell.
            cell = $(row.insertCell(-1));
            cell.html(txtCountry.val());
 
            //Add Button cell.
            cell = $(row.insertCell(-1));
            var btnRemove = $("<input />");
            btnRemove.attr("type", "button");
            btnRemove.attr("onclick", "Remove(this);");
            btnRemove.val("Remove");
            cell.append(btnRemove);
 
            //Clear the TextBoxes.
            txtName.val("");
            txtCountry.val("");
 
            return false;
        });
 
        $("[id*=btnSave]" ).on("click"function () {
            //Loop through the Table rows and build a JSON array.
            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);
            });
 
            //Send the JSON array to Controller using AJAX.
            $.ajax({
                 type: "POST",
                 url: "Default.aspx/InsertCustomers",
                 data: JSON.stringify({ customers: customers }),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function (response) {
                    alert(response.d + " record(s) inserted.");
                 },
                 error: function (response) {
                    alert(response.responseText);
                }
            });
 
            return false;
        });
    });
 
    function Remove(button) {
        //Determine the reference of the Row using the Button.
        var row = $(button).closest("TR");
        var name = $("TD", row).eq(0).html();
        if (confirm("Do you want to delete: " + name)) {
            //Get the reference of the Table.
            var table = $("#tblCustomers")[0];
 
            //Delete the Table row usingit's Index.
            table.deleteRow(row[0].rowIndex);
        }
 
        return false;
    };
</script>
 
 

WebMethod for populating the HTML Table

Inside the WebMethod, records are fetched from customers table and return using Entity Framework.
C#
[WebMethod]
public static List<Customer>GetCustomers()
{
    using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
    {
        List<Customer> customers = (from customer in entities.Customers
                                    select customer).ToList();
        return customers;
    }
}
 
VB.Net
<WebMethod>
Public Shared Function GetCustomers() As List(Of Customer)
    Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
        Dim customers As List(Of Customer) = (From customer In entities.Customers
                                              Select customer).ToList()
        Return customers
    End Using
End Function
 
 

WebMethod for inserting the records

The following WebMethod is executed when the AJAX call is made from the Save All Button is click.
Inside the truncate WebMethod, Generic List collection of Customer class object is received as parameter and all the records of the Customers table are deleted using the TRUNCATE command.
Then, a check is performed if Generic List collection of Customer class object is null then, new Generic List collection of Customer class object is created.
Next, a FOREACH loop is executed over the Generic List collection of Customer class object and the records are inserted into SQL Server database using Entity Framework.
Finally, the Count of inserted record is returned back to the jQuery AJAX function.
C#
[WebMethod]
public static int InsertCustomers(List<Customer> customers)
{
    using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
    {
        //Truncate Table to delete all old records.
        entities.Database.ExecuteSqlCommand("TRUNCATE TABLE [Customers]");
 
        //Check for NULL.
        if  (customers ==  null)
        {
             customers = new List<Customer>();
        }
 
        //Loop and insert records.
        foreach (Customer customer in customers)
        {
            entities.Customers.Add(customer);
        }
        int insertedRecords entities.SaveChanges();
 
        return insertedRecords;
    }
}
 
VB.Net
<WebMethod>
Public Shared Function InsertCustomers(customers As List(Of Customer)) As Integer
    Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
        'Truncate Table to delete all old records.
        entities.Database.ExecuteSqlCommand("TRUNCATE TABLE [Customers]")
 
        'Check for NULL.
        If customers Is Nothing Then
             customers = New List(Of Customer)()
        End If
 
        'Loop and insert records.
        For Each customer As Customer In customers
            entities.Customers.Add(customer)
        Next
        Dim insertedRecords As Integer entities.SaveChanges()
 
        Return insertedRecords
    End Using
End Function
 
 

Screenshot

Insert (Save) Multiple rows (records) to database using Entity Framework in ASP.Net
 
 

Downloads