In this article I will explain with an example, how to add and delete Rows from HTML Table using jQuery AJAX in ASP.Net Core Razor Pages.
Entity Framework will be used to perform Insert and Delete operations in ASP.Net Core Razor Pages.
 
 
Database
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
ASP.Net Core Razor Pages: Add Delete Rows from HTML Table using jQuery AJAX
 
I have already inserted few records in the table.
ASP.Net Core Razor Pages: Add Delete Rows from HTML Table using jQuery AJAX
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Model
The following Model class consists of following properties.
public class CustomerModel
{
    [Key]
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}
 
 
Database Context
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Note: For beginners in ASP.Net Core and Entity Framework, please refer my article ASP.Net Core Razor: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework with ASP.Net Core.
 
using Microsoft.EntityFrameworkCore;
 
namespace Add_Delete_Rows_Table_Core_Razor
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<CustomerModel> Customers { get; set; }
    }
}
 
 
Razor PageModel (Code-Behind)
The Index Model consists of following Handler methods.
Handler method for handling GET operation
Inside this Handler method, all the records from the Customers table are fetched using Entity Framework and copied to a Generic List collection of Customer Model class object.
 
Handler method for Inserting
This Handler method handles call made by the jQuery AJAX function in the Razor Pages.
Inside this Handler method, the received Customer object is inserted into the Customers table and the Customer object is returned.
Note: The following Handler method handles POST call and will return JSON object and hence the return type is set to JsonResult. For more details please refer Using jQuery AJAX in ASP.Net Core Razor Pages.
 
Handler method for Deleting
This Handler method handles call made by the jQuery AJAX function in the Razor Page.
Inside this Handler method, the CustomerId value is received as parameter. The CustomerId value is used to reference the Customer record in the Customer Model.
Finally, once the record is referenced, the Customer record is deleted from the Customers table.
public class IndexModel : PageModel
{
    private DBCtx Context { get; }
    public IndexModel(DBCtx _context)
    {
        this.Context = _context;
    }
 
    public List<CustomerModel> Customers { get; set; }
 
    public void OnGet()
    {
        this.Customers = this.Context.Customers.ToList();
        this.Customers.Insert(0, new CustomerModel());
    }
 
    [ValidateAntiForgeryToken]
    public JsonResult OnPostInsertCustomer(CustomerModel customer)
    {
        this.Context.Customers.Add(customer);
        this.Context.SaveChanges();
        return new JsonResult(customer);
    }
 
    [ValidateAntiForgeryToken]
    public EmptyResult OnPostDeleteCustomer(int CustomerId)
    {
        CustomerModel customer = (from c in this.Context.Customers
                                  where c.CustomerId == CustomerId
                                  select c).FirstOrDefault();
        this.Context.Customers.Remove(customer);
        this.Context.SaveChanges();
        return new EmptyResult();
    }
}
 
 
Razor Page (HTML)
Inside the Razor Page, an HTML Table is created with some HTML SPAN elements.
Display
For displaying the records, an HTML Table is used. A loop will be executed over the public property which will generate the HTML Table rows with the Customer records.
 
Insert
Below the Table there’s another table consisting of two TextBoxes and a Button for adding row (data).
When the Add button is clicked the name and the country values are fetched from their respective TextBoxes and then passed to the InsertCustomer Handler method using jQuery AJAX.
Once the response is received, a new row is appended to the HTML table using the AppendRow function.
 
Delete
When the Delete link is clicked, the reference of the HTML Table row is determined and the value of the CustomerId is fetched and passed to the DeleteCustomer Handler method using jQuery AJAX.
Once the response is received, the respective row is removed from the HTML Table row.
@page
@model Add_Delete_Rows_Table_Core_Razor.Pages.IndexModel
@using Add_Delete_Rows_Table_Core_Razor.Models
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @Html.AntiForgeryToken()
    <table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
        <tr>
            <th style="width:100px">Customer Id</th>
            <th style="width:150px">Name</th>
            <th style="width:150px">Country</th>
            <th style="width:40px"></th>
        </tr>
        @foreach (CustomerModel customer in Model.Customers)
        {
            <tr>
                <td class="CustomerId">
                    <span>@customer.CustomerId</span>
                </td>
                <td class="Name">
                    <span>@customer.Name</span>
                </td>
                <td class="Country">
                    <span>@customer.Country</span>
                </td>
                <td>
                    <a class="Delete" id="btnDelete" href="javascript:;">Delete</a>
                </td>
            </tr>
        }
    </table>
    <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: 200px">
                <br />
                <input type="button" id="btnAdd" value="Add" />
            </td>
        </tr>
    </table>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            //Remove the dummy row if data present.
            if ($("#tblCustomers tr").length > 2) {
                $("#tblCustomers tr:eq(1)").remove();
            } else {
                var row = $("#tblCustomers tr:last-child");
                row.find(".Delete").hide();
                row.find("span").html('&nbsp;');
            }
        });
        $("body").on("click", "#btnAdd", function () {
            var name = $("#txtName").val();
            var country = $("#txtCountry").val();
            var token = $('input:hidden[name="__RequestVerificationToken"]').val();
            $.ajax({
               type: "POST",
                url: "/Index?handler=InsertCustomer",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN", token);
                },
                data: { Name: name, Country: country },
                success: function (r) {
                    var row = $("#tblCustomers tr:last-child");
                    if ($("#tblCustomers tr:last-child span").eq(0).html() != "&nbsp;") {
                        row = row.clone();
                    }
                    AppendRow(row, r.CustomerId, r.Name, r.Country);
                    txtName.val("");
                    txtCountry.val("");
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
 
        function AppendRow(row, customerId, name, country) {
            //Bind CustomerId.
            $(".CustomerId", row).find("span").html(customerId);
 
            //Bind Name.
            $(".Name", row).find("span").html(name);
            $(".Name", row).find("input").val(name);
 
            //Bind Country.
            $(".Country", row).find("span").html(country);
            $(".Country", row).find("input").val(country);
 
            row.find(".Delete").show();
            $("#tblCustomers").append(row);
        };
 
        $("body").on("click", "#tblCustomers .Delete", function () {
            if (confirm("Do you want to delete this row?")) {
                var row = $(this).closest("tr");
                var token = $('input:hidden[name="__RequestVerificationToken"]').val();
                $.ajax({
                    type: "POST",
                    url: "/Index?handler=DeleteCustomer",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN", token);
                    },
                    data: { CustomerId: row.find("span").html() },
                    success: function (r) {
                        if ($("#tblCustomers tr").length > 2) {
                            row.remove();
                        } else {
                            row.find(".Delete").hide();
                            row.find("span").html('&nbsp;');
                        }
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            }
        });
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: Add Delete Rows from HTML Table using jQuery AJAX
 
 
Downloads