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

Database

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

Model

The Model class consists of following properties.
public class Customer
{
    public int CustomerId { getset; }
    public string Name { getset; }
    public string Country { getset; }
}
 
 

Database Context

Once the Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
Note: For beginners in ASP.Net Core (.Net Core 8) Razor Pages and Entity Framework, please refer my article .Net Core 8: Entity Framework Tutorial in ASP.Net Core Razor Pages. It covers all the information needed for connecting and configuring Entity Framework with ASP.Net Core (.Net Core 8) Razor pages.
 
using Microsoft.EntityFrameworkCore;
 
namespace WebGrid_CRUD_Core_Razor
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<Customer> Customers { getset; }
    }
}
 
 

Index PageModel (Code-Behind)

Inside the PageModel, first a private property (Context) of DbContext is created.
Then, the DbContext class is injected into the Constructor (IndexModel) using Dependency Injection method and the injected object is assigned to the private property Context.
Finally, a public property of Generic List collection of Customer class is created.
The PageModel 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 stored as Generic List collection of Customer class (explained earlier).
A dummy (empty) record is also added to the Generic List collection at first position (Index).
Note: The empty record is inserted so that it can be used to add new row to the WebGrid by the Client Side jQuery functions.
 

Handler method for Inserting

This Handler method accepts the Customer class object as parameter.

Attribute

ValidateAntiForgeryToken – The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Inside this Handler method, the received Customer class object is inserted into the Customers table using Entity Framework and the updated Customer object with generated CustomerId is returned back to the Razor Page as JSON object.
 

Handler method for Updating

This Handler method accepts the Customer class object as parameter.

Attribute

ValidateAntiForgeryToken – The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Inside this Handler method, the Customer object is received as parameter and the CustomerId value of the received Customer object is used to reference the Customer record in the Customer Entities.
Once the record is referenced, the values of Name and Country are updated using Entity Framework and the changes are updated into the Customers table.
Finally, the EmptyResult (NULL) is returned.
 

Handler method for Deleting

This Handler method accepts the Customer class object as parameter.

Attribute

ValidateAntiForgeryToken – The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Inside this Handler method, the CustomerId value is received as parameter. The CustomerId value is used to reference the Customer record in the Customer Entities.
Once the record is referenced, the Customer record is deleted from the Customers table using Entity Framework and the updated Customer object is returned back to the Razor Page as JSON object.
public class IndexModel : PageModel
{
    private DBCtx Context { get; }
 
    public IndexModel(DBCtx _context)
    {
        this.Context = _context;
    }
 
    public List<Customer> Customers { getset; }
 
    public void OnGet()
    {
        List<Customer> customers = this.Context.Customers.ToList();
 
        //Add a Dummy Row.
        customers.Insert(0, new Customer()); 
 
        this.Customers = customers;
    }
 
    [ValidateAntiForgeryToken]
    public IActionResult OnPostInsertCustomer(Customer customer)
    {
        this.Context.Customers.Add(customer);
        this.Context.SaveChanges();
        return new JsonResult(customer);
    }
 
    [ValidateAntiForgeryToken]
    public IActionResult OnPostUpdateCustomer(Customer customer)
    {
        Customer updatedCustomer = (from c in this.Context.Customers
                                    where c.CustomerId == customer.CustomerId
                                    select c).FirstOrDefault();
        updatedCustomer.Name = customer.Name;
        updatedCustomer.Country = customer.Country;
        this.Context.SaveChanges();
 
        return new EmptyResult();
    }
 
    [ValidateAntiForgeryToken]
    public IActionResult OnPostDeleteCustomer(int customerId)
    {
        Customer customer = (from c in this.Context.Customers
                             where c.CustomerId == customerId
                             select c).FirstOrDefault();
        this.Context.Customers.Remove(customer);
        this.Context.SaveChanges();
 
        return new JsonResult(customer);
    }
}
 
 

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.

Display

The WebGrid is initialized with the Model i.e. IEnumerable collection of Customer Model class object is passed to the Grid function of the MVC6 Grid HTML Helper class.
Note: For more information on usage of WebGrid in ASP.Net Core, please refer WebGrid Step By Step Tutorial with example in ASP.Net Core MVC.
 
Below the WebGrid, two HTML INPUT TextBoxes and an HTML INPUT Button has been placed for inserting Name and Country value. The Button has been assigned with a jQuery click event handler.
 

Insert

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 the 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
@model WebGrid_CRUD_Core_Razor.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@using NonFactors.Mvc.Grid;
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @Html.AntiForgeryToken()
    <div id="WebGrid" style="width:600px;">
        @(Html.Grid(Model.Customers).Build(columns =>
            {
                 columns.Add().Titled("Customer Id").Css("CustomerId")
                .RenderedAs(model => Html.Raw($"<span class='label'>" + model.CustomerId + "</span>"));
 
                 columns.Add().Titled("Name").Css("Name")
                .RenderedAs(model => Html.Raw($"<span><span class='label'>" + model.Name + "</span>" +
                    " + model.Name + "' style='display:none' /></span>"));
 
                 columns.Add().Titled("Country").Css("Country")
                .RenderedAs(model => Html.Raw($"<span><span class='label'>" + model.Country + "</span>" +
                    "<input class='text' type='text' value='" + model.Country + "' style='display:none' /></span>"));
 
                 columns.Add()
                .RenderedAs(model => Html.Raw($"<span class='/'>" +
                    "<a class='Edit' href='javascript:;'>Edit</a>" +
                    "<a class='Update' href='javascript:;' style='display:none'>Update</a>&nbsp;" +
                    "<a class='Cancel' href='javascript:;' style='display:none'>Cancel</a>&nbsp;" +
                    "<a class='Delete' href='javascript:;'>Delete</a>" +
                    "</span>"));
            })
        )
    </div>
    <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="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var row = $("#WebGrid TBODY tr:eq(0)");
            if ($("#WebGrid TBODY tr").length > 1) {
                row.remove();
             } else {
                row.find(".label").html("");
                row.find(".text").val("");
                row.find("./").hide();
            }
        });
 
        function AppendRow(row, customerId, name, country) {
            //Bind CustomerId.
            $(".CustomerId", row).find(".label").html(customerId);
 
            //Bind Name.
            $(".Name", row).find(".label").html(name);
            $(".Name", row).find(".text").val(name);
 
            //Bind Country.
            $(".Country", row).find(".label").html(country);
            $(".Country", row).find(".text").val(country);
            row.find("./").show();
            $("#WebGrid TBODY").append(row);
        };
 
        //Add event handler.
        $("body").on("click""#btnAdd"function () {
            var txtName = $("#txtName");
            var txtCountry = $("#txtCountry");
            $.ajax({
                  type: "POST",
                  url: "/Index?handler=InsertCustomer",
                  data: { Name: txtName.val(), Country: txtCountry.val() },
                  beforeSend: function (xhr) {
                     xhr.setRequestHeader("XSRF-TOKEN",
                         $('input:hidden[name="__RequestVerificationToken"]').val());
                  },
                  success: function (r) {
                    var row = $("#WebGrid TBODY tr:last-child").clone();
                    if (row.find(".label").is(":empty")) {
                        $("#WebGrid TBODY tr:last-child").remove();
                    }
                    AppendRow(row, r.CustomerId, r.Name, r.Country);
                    txtName.val("");
                    txtCountry.val("");
                }
            });
        });
 
        //Edit event handler.
        $("body").on("click""#WebGrid TBODY .Edit"function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find(".text").length > 0) {
                    $(this).find(".text").show();
                    $(this).find(".label").hide();
                }
            });
            row.find(".Update").show();
            row.find(".Cancel").show();
            row.find(".Delete").hide();
            $(this).hide();
        });
 
        //Update event handler.
        $("body").on("click""#WebGrid TBODY .Update"function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find(".text").length > 0) {
                    var span = $(this).find(".label");
                    var input = $(this).find(".text");
                    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(".label").html();
            customer.Name = row.find(".Name").find(".label").html();
            customer.Country = row.find(".Country").find(".label").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""#WebGrid TBODY .Cancel"function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find(".text").length > 0) {
                    var span = $(this).find(".label");
                    var input = $(this).find(".text");
                    input.val(span.html());
                    span.show();
                    input.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Delete").show();
            row.find(".Update").hide();
            $(this).hide();
        });
 
        //Delete event handler.
        $("body").on("click""#WebGrid TBODY .Delete"function () {
            if (confirm("Do you want to delete this row?")) {
                var row = $(this).closest("tr");
                var customerId = row.find(".label").html();
                $.ajax({
                    type: "POST",
                    url: "/Index?handler=DeleteCustomer",
                    data: { CustomerId: customerId },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    success: function (response) {
                        if ($("#WebGrid TBODY tr").length == 1) {
                            row.find(".label").html("");
                            row.find(".text").val("");
                            row.find("./").hide();
                         } else {
                            row.remove();
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>
 
 

Screenshot

ASP.Net Core Razor Pages: Select Insert Edit Update and Delete in WebGrid
 
 

Downloads