This example demonstrates how to bind DataGrid to a controller action and implement CRUD operations (such as Load, Insert, Update, and Delete) in a Razor Pages project.
Specify the Controller, LoadAction, UpdateAction, InsertAction, and DeleteAction properties so that the DataGrid's DataSource can perform CRUD operations. In the corresponding controller, implement data operations in the actions.
Note that it is necessary to set up routing correctly in Razor Pages and controllers.
Files to Review
Documentation
More Examples
Example Code
C#using System.Linq;
using DevExtreme.AspNet.Data;
using DevExtreme.AspNet.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using T845675test.Models;
namespace CS.Controllers {
[ApiController]
[Route("api/[controller]")]
public class DataGridEmployeesController : Controller {
InMemoryEmployeesDataContext _data;
public DataGridEmployeesController(IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache) {
_data = new InMemoryEmployeesDataContext(httpContextAccessor, memoryCache);
}
[HttpGet]
public IActionResult Get(DataSourceLoadOptions loadOptions) {
return Json(DataSourceLoader.Load(_data.Employees, loadOptions));
}
[HttpPost]
public IActionResult Post([FromForm]string values) {
var newEmployee = new Employee();
JsonConvert.PopulateObject(values, newEmployee);
if (!TryValidateModel(newEmployee))
return BadRequest();
_data.Employees.Add(newEmployee);
_data.SaveChanges();
return Ok();
}
[HttpPut]
public IActionResult Put([FromForm]int key, [FromForm]string values) {
var employee = _data.Employees.First(a => a.ID == key);
JsonConvert.PopulateObject(values, employee);
if (!TryValidateModel(employee))
return BadRequest();
_data.SaveChanges();
return Ok();
}
[HttpDelete]
public void Delete([FromForm]int key) {
var employee = _data.Employees.First(a => a.ID == key);
_data.Employees.Remove(employee);
_data.SaveChanges();
}
}
}
Razor@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h2 >How to implement CRUD operations via API controllers in an ASP.NET Core with Razor Pages project</h2>
</div>
@(Html.DevExtreme().DataGrid<T845675test.Models.Employee>()
.ID("grid")
.Height(400)
.DataSource(d => d.Mvc()
.Controller("DataGridEmployees")
.LoadAction("Get")
.UpdateAction("Put")
.InsertAction("Post")
.DeleteAction("Delete")
.Key("ID")
)
.ShowBorders(true)
.Paging(paging => paging.Enabled(false))
.Columns(columns => {
columns.Add().DataField("Prefix").Caption("Title");
columns.Add().DataField("FirstName");
columns.Add().DataField("LastName");
columns.Add().DataField("Position").Width(130);
columns.Add().DataField("BirthDate").DataType(GridColumnDataType.Date).Width(125);
})
.Editing(e => e
.Mode(GridEditMode.Cell)
.RefreshMode(GridEditRefreshMode.Reshape)
.AllowAdding(true)
.AllowDeleting(true)
.AllowUpdating(true)
)
)