In this article I will explain with an example, how to perform CRUD i.e. Create, Read, Update and Delete operation using Dapper library in ASP.Net Core Razor Pages.
Note: For beginners in ASP.Net Core 7 Razor Pages, please refer my article ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program example.
 
 

Installing Dapper package using Nuget

In order to install Dapper library using Nuget, please refer my article Install Dapper from Nuget in Visual Studio.
 
 

Configuring default Camel Case JSON Output

In order to configure default Camel Case JSON Output, please refer my article ASP.Net Core 7: Changing the default Camel Case JSON Output.
 
 

Database

I have made use of the following table Customers with the schema as follows.
ASP.Net Core Razor CRUD: Select Insert Edit Update and Delete using Dapper
 
I have already inserted few records in the table.
ASP.Net Core Razor CRUD: Select Insert Edit Update and Delete using Dapper
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 

Namespaces

You will need to import the following namespaces.
using Dapper;
using System.Data.SqlClient;
using Microsoft.AspNetCore.Mvc;
 
 

Model

The Model class consists of following properties.
public class CustomerModel
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}
 
 

Razor PageModel (Code-Behind)

The PageModel consists of following Handler methods.

Handler method for handling GET operation

Inside this Handler method, first the connection is read from the ConnectionStrings section of the AppSettings.json file.
Then, using Query method of Dapper library records from the Customers table are fetched and stored as a Generic List collection of CustomerModel class.
Then, new instance of CustomerModel class is added to the list at 0th index which means the new customer will be the first element in the list.
 

Handler method for handling Insert operation

This Handler method accepts the CustomerModel class object as parameter.

Attribute

ValidateAntiForgeryToken – The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Inside this Handler method, first the connection is read from the ConnectionStrings section of the AppSettings.json file.
Then, using the ExecuteScalar method of Dapper library record is inserted into the SQL Server database.
Note: For more details on ExecuteScalar method, please refer my article Understanding Dapper ExecuteScalar in C# and VB.Net.
 
Finally, the CustomerModel class object with generated CustomerId is returned back to the Razor Page (HTML) as JSON object.
 

Handler method for handling Update operation

This Handler method accepts the CustomerModel class object as parameter.

Attribute

ValidateAntiForgeryToken – The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Inside this Handler method, first the connection is read from the ConnectionStrings section of the AppSettings.json file.
Then, using the Execute method of Dapper library record is updated into the SQL Server database.
Note: For more details on Execute method, please refer my article Understanding Dapper Execute in C# and VB.Net.
 
Finally, the EmptyResult (NULL) is returned.
 

Handler method for handling Delete operation

This Handler method accepts the CustomerModel class object as parameter.

Attribute

ValidateAntiForgeryToken – The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Inside this Handler method, first the connection is read from the ConnectionStrings section of the AppSettings.json file.
Then, using Execute method of Dapper library record is deleted from the SQL Server database.
Note: For more details on Execute method, please refer my article Understanding Dapper Execute in C# and VB.Net.
 
Finally, the EmptyResult (NULL) is returned.
public class IndexModel : PageModel
{
    public IConfiguration Configuration { get; set; }
    public List<CustomerModel> Customers { get; set; }
    public IndexModel(IConfiguration configuration)
    {
        this.Configuration = configuration;
    }
 
    public void OnGet()
    {
        string sql = "SELECT CustomerId, Name, Country FROM Customers";
        string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
        using (SqlConnection con = new SqlConnection(constr))
        {
            Customers = con.Query<CustomerModel>(sql).ToList();
            Customers.Insert(0, new CustomerModel());
       }
    }
 
    [ValidateAntiForgeryToken]
    public IActionResult OnPostInsertCustomer(CustomerModel customer)
    {
        string sql = "INSERT INTO Customers VALUES (@Name, @Country)";
        sql += " SELECT SCOPE_IDENTITY()";
        string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
        using (SqlConnection con = new SqlConnection(constr))
        {
            customer.CustomerId = Convert.ToInt32(con.ExecuteScalar(sql, Customer));
            return new JsonResult(customer);
        }
    }
 
    [ValidateAntiForgeryToken]
    public IActionResult OnPostUpdateCustomer(CustomerModel customer)
    {
        string sql = "UPDATE Customers SET Name=@Name, Country=@Country WHERE CustomerId=@CustomerId";
        string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
        using (SqlConnection con = new SqlConnection(constr))
        {
            con.Execute(sql, customer);
        }
        return new EmptyResult();
    }
 
    [ValidateAntiForgeryToken]
    public IActionResult OnPostDeleteCustomer(CustomerModel customer)
    {
        string sql = "DELETE FROM Customers WHERE CustomerId = @CustomerId";
        string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
        using (SqlConnection con = new SqlConnection(constr))
        {
            con.Execute(sql, customer);
        }
        return new EmptyResult();
    }
}
 
 

Razor Page (HTML)

HTML Markup

Inside the Razor Page, the Anti-Forgery Token has been added to Razor Page using the AntiForgeryToken function of the HTML Helper class.
Inside the HTML of the Razor Page, the following script file is inherited.
1. jquery.min.js
 

Display

For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
 

Insert

The HTML of the Razor Page also consists of HTML TextBoxes and a Button for inserting records into the database.
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 call and URL of the Handler method is specified in this case /Index?handler= InsertCustomer.
Once the response is received, a new row is appended to the HTML table using the AppendRow function.
 

Edit

When the Edit Button is clicked, the reference of the HTML Table row is determined and the HTML SPAN elements are made hidden while the TextBoxes are made visible in the Name and Country columns of the HTML Table.
 

Update

When the Update Button is clicked, the reference of the HTML Table row is determined and the updated values are fetched from their respective TextBoxes of Name and Country columns while the CustomerId is determined from the HTML SPAN element of the CustomerId column.
The values of CustomerId, Name and Country are passed to the UpdateCustomer Handler method using jQuery AJAX call and URL of the Handler method is specified in this case /Index?handler= UpdateCustomer.
Once the response is received, the HTML SPAN elements are made visible and the TextBoxes are made hidden for the Name and Country columns of the HTML Table row.
 

Cancel

When the Cancel Button is clicked, the reference of the HTML Table row is determined and the HTML SPAN elements are made visible while the TextBoxes are made hidden in the Name and Country columns of the HTML Table row.
 

Delete

When the Delete Button 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 call and URL of the Handler method is specified in this case /Index?handler= DeleteCustomer.
Once the response is received, the respective row is removed from the HTML Table row.
@page
@using CRUD_Dapper_Core_Razor.Models
@model CRUD_Dapper_Core_Razor.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @Html.AntiForgeryToken()
    <table id="tblCustomers" 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:150px"></th>
        </tr>
        @foreach (CustomerModel customer in Model.Customers)
        {
            <tr>
                <td class="CustomerId">
                    <span>@customer.CustomerId</span>
                </td>
                <td class="Name">
                    <span>@customer.Name</span>
                    <input type="text" value="@customer.Name" style="display:none" />
                </td>
                <td class="Country">
                    <span>@customer.Country</span>
                    <input type="text" value="@customer.Country" style="display:none" />
                </td>
                <td>
                    <a class="Edit" href="javascript:;">Edit</a>
                    <a class="Update" href="javascript:;" style="display:none">Update</a>
                    <a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
                    <a class="Delete" 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/3.7.1/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(".Edit").hide();
                row.find("span").html('&nbsp;');
            }
 
            //Add event handler.
            $("body").on("click", "#btnAdd", function () {
                var name = $("#txtName").val();
                var country = $("#txtCountry").val();
                $.ajax({
                    type: "POST",
                    url: "/Index?handler=InsertCustomer",
                    data: { Name: name, Country: country },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    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("");
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
 
            //Delete event handler.
            $("body").on("click", "#tblCustomers .Delete", function () {
                if (confirm("Do you want to delete this row?")) {
                    var row = $(this).closest("tr");
                    $.ajax({
                        type: "POST",
                        url: "/Index?handler=DeleteCustomer",
                        data: { CustomerId: row.find("span").html() },
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
                        success: function (response) {
                            if ($("#tblCustomers tr").length > 2) {
                                row.remove();
                            } else {
                                row.find(".Delete").hide();
                                row.find(".Edit").hide();
                                row.find("span").html('&nbsp;');
                            }
                        }
                    });
                }
            });
 
            //Edit event handler.
            $("body").on("click", "#tblCustomers .Edit", function () {
                var row = $(this).closest("tr");
                $("td", row).each(function () {
                    if ($(this).find("input").length > 0) {
                        $(this).find("input").show();
                        $(this).find("span").hide();
                    }
                });
                row.find(".Update").show();
                row.find(".Cancel").show();
                row.find(".Delete").hide();
                $(this).hide();
            });
 
            //Update event handler.
            $("body").on("click", "#tblCustomers .Update", function () {
                var row = $(this).closest("tr");
                $("td", row).each(function () {
                    if ($(this).find("input").length > 0) {
                        var span = $(this).find("span");
                        var input = $(this).find("input");
                        span.html(input.val());
                        span.show();
                        input.hide();
                    }
                });
                row.find(".Edit").show();
                row.find(".Delete").show();
                row.find(".Cancel").hide();
                $(this).hide();
 
                var customer = {};
                customer.CustomerId = row.find(".CustomerId").find("span").html();
                customer.Name = row.find(".Name").find("span").html();
                customer.Country = row.find(".Country").find("span").html();
                $.ajax({
                    type: "POST",
                    url: "/Index?handler=UpdateCustomer",
                    data: customer,
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                });
            });
 
            //Cancel event handler.
            $("body").on("click", "#tblCustomers .Cancel", function () {
                var row = $(this).closest("tr");
                $("td", row).each(function () {
                    if ($(this).find("input").length > 0) {
                        var span = $(this).find("span");
                        var input = $(this).find("input");
                        input.val(span.html());
                        span.show();
                        input.hide();
                    }
                });
                row.find(".Edit").show();
                row.find(".Delete").show();
                row.find(".Update").hide();
                $(this).hide();
            });
 
            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();
                row.find(".Edit").show();
                $("#tblCustomers").append(row);
            };
        });
    </script>
</body>
</html>
 
 

Screenshot

ASP.Net Core Razor CRUD: Select Insert Edit Update and Delete using Dapper
 
 

Downloads