Entity framework core sql server db context as data source for razor page grids

1 Answer 1267 Views
Grid
FreshDonuts
Top achievements
Rank 1
FreshDonuts asked on 28 May 2021, 12:22 AM

Hello,

I saw an example by you guys for razor pages but I need it done for CRUD operations for a data source in the sql server. Assume I have appsettings.json file setup with the correct sql server connection string along with ApplicationDBContext setup in the startup.cs file in the configureservices section to allow dependency injection and the ApplicationDBContext was passed through a constructor for the specified model referenced in the code below to utilize dependency injection. What else would I need to change in the code to allow me to do CRUD operations on razor pages that utilizes entity framework core sql server as its data source?


@page
@model Telerik.Examples.RazorPages.Pages.Grid.GridCrudOperationsModel
@{
    ViewData["Title"] = "GridCrudOperations";
}

<h1>GridCrudOperations</h1>

@using Telerik.Examples.RazorPages.Models
@using Kendo.Mvc.UI

@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@Html.AntiForgeryToken()

@(Html.Kendo().Grid<OrderViewModel>().Name("grid")
                .Groupable()
                .Sortable()
                .Editable()
                .Scrollable()
                .ToolBar(x => {
                    x.Create();
                    x.Excel();
                })
                .Columns(columns =>
                {
                    columns.Bound(column => column.Freight);
                    columns.Bound(column => column.ShipName);
                    columns.Bound(column => column.ShipCity);
                    columns.Command(column =>
                    {
                        column.Edit();
                        column.Destroy();
                    });
                })
                 .Excel(excel => excel
                            .FileName("Export.xlsx")
                            .Filterable(true)
                            .ProxyURL("/Grid/GridCrudOperations?handler=Save")
                        )
                .DataSource(ds => ds.Ajax()
                       .Read(r => r.Url("/Grid/GridCrudOperations?handler=Read").Data("forgeryToken"))
                       .Update(u => u.Url("/Grid/GridCrudOperations?handler=Update").Data("forgeryToken"))
                       .Create(c => c.Url("/Grid/GridCrudOperations?handler=Create").Data("forgeryToken"))
                       .Destroy(d => d.Url("/Grid/GridCrudOperations?handler=Destroy").Data("forgeryToken"))
                       .Model(m => m.Id(id => id.OrderID))
                    .PageSize(10)
                )
                .Pageable()
)

<script>
    function forgeryToken() {
        return kendo.antiForgeryTokens();
    }
</script>

 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Telerik.Examples.RazorPages.Models;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Telerik.Examples.RazorPages.Pages.Grid
{
    public class GridCrudOperationsModel : PageModel
    {
        public static IList<OrderViewModel> orders;

        public void OnGet()
        {
            if (orders == null)
            {
                orders = new List<OrderViewModel>();

                Enumerable.Range(0, 50).ToList().ForEach(i => orders.Add(new OrderViewModel
                {
                    OrderID = i + 1,
                    Freight = i * 10,
                    ShipName = "ShipName " + i,
                    ShipCity = "ShipCity " + i
                }));

            }
        }

        public JsonResult OnPostRead([DataSourceRequest] DataSourceRequest request)
        {
            return new JsonResult(orders.ToDataSourceResult(request));
        }

        public JsonResult OnPostCreate([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            order.OrderID = orders.Count + 2;
            orders.Add(order);

            return new JsonResult(new[] { order }.ToDataSourceResult(request, ModelState));
        }

        public JsonResult OnPostUpdate([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            orders.Where(x => x.OrderID == order.OrderID).Select(x => order);

            return new JsonResult(new[] { order }.ToDataSourceResult(request, ModelState));
        }

        public JsonResult OnPostDestroy([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            orders.Remove(orders.FirstOrDefault(x => x.OrderID == order.OrderID));

            return new JsonResult(new[] { order }.ToDataSourceResult(request, ModelState));
        }

        [HttpPost]
        public ActionResult OnPostSave(string contentType, string base64, string fileName)
        {
            var fileContents = Convert.FromBase64String(base64);

            return File(fileContents, contentType, fileName);
        }
    }
}

 

1 Answer, 1 is accepted

Sort by
0
Aleksandar
Telerik team
answered on 31 May 2021, 10:57 AM

Hello FreshDonuts,

The provided code snippet indeed demonstrates how to implement CRUD operations when using the Telerik UI for ASP.NET Core and the Grid component in RazorPages scenario. In general, the Grid is a UI component that provides options for executing CRUD data operations, along with paging, sorting, filtering, grouping, and editing, and provides possibilities to customize the way the data is presented and manipulated. It is the developer's responsibility to handle the backend operations concerning the CRUD operations and services implementation as they differ from project to project and are based on custom requirements for the project.

In case you experience issue setting up such services I can suggest the following resources:

Razor Pages with EF Core in ASP.NET Core - CRUD

There are numerous other resources available and you can check other tutorials on this as well, for example this one. If you need details on the particular services behind the Telerik UI for ASP.NET Core Demos, for example the InLine editing demo,  make sure to click on the View Source tab to review the source code and the example implementation of such a service.

Regards,
Aleksandar
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
Grid
Asked by
FreshDonuts
Top achievements
Rank 1
Answers by
Aleksandar
Telerik team
Share this question
or