Implementing DevExtreme DataGrid in ASP.NET Core: A Step-by-Step Tutorial

 Implementing DevExtreme DataGrid in ASP.NET Core: A Step-by-Step Tutorial

Efficient data presentation is vital in modern web applications that rely on data. ASP.NET Core projects can benefit from the robust capabilities of the DevExtreme DataGrid, which allows for seamless display and manipulation of extensive datasets. This all-inclusive tutorial will guide you through the entire integration process, starting from installing the DevExtreme DataGrid package, all the way to utilizing advanced functionalities such as Excel export and filtering.

1. DevExtreme Integration in ASP.NET Core

To begin, you’ll need to add DevExtreme to your ASP.NET Core project. This involves installing the necessary NuGet packages and including the required CSS and JavaScript files.

First, install the DevExtreme.AspNet.Core NuGet package:

dotnet add package DevExtreme.AspNet.Core

Next, add the following lines to your _Layout.cshtml file to include the DevExtreme CSS and JavaScript files:

<head>
    <!-- Other head elements -->
    <link href="~/css/devextreme/dx.light.css" rel="stylesheet" />
</head>
<body>
    <!-- Your content -->
    <script src="~/js/devextreme/dx.all.js"></script>
</body>

2. Package Installation and Setup

In addition to the DevExtreme package, you’ll need to install ExcelJS for Excel export functionality:

npm install exceljs file-saver
<script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.3.0/exceljs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>

3. Creating Razor Pages with DataGrid

Now, let’s create a Razor page that implements the DevExtreme DataGrid. Here’s a simplified example:

@(Html.DevExtreme().DataGrid<ProductInfo>()
    .ID("productDataGrid")
    .DataSource(Model)
    .ShowBorders(true)
    .Columns(columns => {
        columns.AddFor(m => m.ProductName);
        columns.AddFor(m => m.Category.Name);
        columns.AddFor(m => m.Price).Format("currency");
        columns.AddFor(m => m.Status).CellTemplate(new JS("changeStatusColor"));
        columns.AddFor(m => m.LastUpdated).DataType(GridColumnDataType.Date);
    })
    .Paging(p => p.PageSize(10))
    .Pager(p => p
        .ShowPageSizeSelector(true)
        .AllowedPageSizes(new[] { 5, 10, 20 })
        .ShowInfo(true)
    )
    .FilterRow(f => f.Visible(true))
    .HeaderFilter(f => f.Visible(true))
    .GroupPanel(p => p.Visible(true))
    .Grouping(g => g.AutoExpandAll(false))
    .RemoteOperations(true)
    .Summary(s => s
        .TotalItems(totalItems => {
            totalItems.AddFor(m => m.Price).SummaryType(SummaryType.Sum);
            totalItems.AddFor(m => m.ProductName).SummaryType(SummaryType.Count);
        })
    )
    .Export(e => e.Enabled(true).AllowExportSelectedData(true))
    .OnExporting("exporting")
    .Selection(s => s.Mode(SelectionMode.Multiple))
    .Sorting(sorting => sorting.Mode(GridSortingMode.Multiple))
)

This example showcases various features of DevExtreme DataGrid in ASP.NET Core, including paging, filtering, grouping, sorting, and exporting.

4. Implementing Excel Export Functionality in DevExtreme DataGrid

To enable Excel export in your DevExtreme DataGrid for ASP.NET Core, add the following JavaScript function:

function exporting(e) {
    var workbook = new ExcelJS.Workbook();
    var worksheet = workbook.addWorksheet('Products');

    DevExpress.excelExporter.exportDataGrid({
        component: e.component,
        worksheet: worksheet,
        autoFilterEnabled: true
    }).then(function () {
        workbook.xlsx.writeBuffer().then(function (buffer) {
            saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'ProductList.xlsx');
        });
    });
    e.cancel = true;
}

This function creates an Excel workbook, adds a worksheet, and exports the DataGrid data to it. The resulting file is then saved and downloaded by the user.

5. Adding Search and Filtering Capabilities

DevExtreme DataGrid provides built-in search and filtering features. You can enable them as follows:

.FilterRow(filterRow => filterRow.Visible(true))
.HeaderFilter(headerFilter => headerFilter.Visible(true))
.SearchPanel(searchPanel => searchPanel.Visible(true).Width(240))

These settings add a filter row, header filters, and a search panel to your DataGrid, allowing users to easily find the data they need.

6. Passing Data from Controller to View

In your controller, prepare the data and pass it to the view:

public IActionResult Index()
{
    var products = _context.Products
        .Include(p => p.Category)
        .ToList();
    return View(products);
}

This code fetches the products from the database, including related category information, and passes it to the view where it can be used as the DataSource for your DevExtreme DataGrid.

In your view, you can then use this data as the DataSource for your DataGrid.

7. Advanced Customization Techniques for DevExtreme DataGrid in ASP.NET Core

DevExtreme DataGrid offers numerous customization options. Here are a few advanced techniques:

  1. Custom cell templates:
columns.AddFor(m => m.Status).CellTemplate(new JS("changeStatusColor"));

2.Conditional formatting:

function changeStatusColor(container, options) {
    var status = options.data.Status;
    var $badge = $("<div>").addClass("badge").text(status);
    
    if (status === "In Stock") {
        $badge.addClass("badge-success");
    } else if (status === "Low Stock") {
        $badge.addClass("badge-warning");
    } else {
        $badge.addClass("badge-danger");
    }
    
    container.append($badge);
}

3.Custom summary calculations:

.Summary(s => s
    .CustomItems(items => {
        items.Add()
            .Column("Price")
            .SummaryType(SummaryType.Custom)
            .ValueFormat("currency")
            .DisplayFormat("Average Price: {0}")
            .ShowInColumn("Price")
            .CustomizeText("customizeAveragePrice");
    })
)

8. Performance Optimization for Large Datasets in DevExtreme DataGrid

When working with large datasets in DevExtreme DataGrid for ASP.NET Core, consider these optimization techniques:

  1. Enable remote operations:
.RemoteOperations(true)

2.Implement server-side paging, sorting, and filtering in your controller:

public IActionResult GetProducts(DataSourceLoadOptions loadOptions)
{
    var query = _context.Products.AsQueryable();
    
    // Apply filtering, sorting, and paging
    return Json(DataSourceLoader.Load(query, loadOptions));
}

3.Use virtual scrolling for very large datasets:

.Scrolling(scrolling => scrolling.Mode(GridScrollingMode.Virtual))

By implementing these advanced features and optimization techniques, you can create a highly performant and user-friendly DevExtreme DataGrid in your ASP.NET Core application.

Conclusion

Implementing DevExtreme DataGrid in ASP.NET Core: A Step-by-Step Tutorial When working with large datasets in DevExtreme DataGrid for ASP.NET Core, implement server-side paging, sorting, and filtering in your controller. Additionally, use virtual scrolling for very large datasets. By implementing these advanced features and optimization techniques, you can create a highly performant and user-friendly DevExtreme DataGrid in your ASP.NET Core application. Conclusion: Implementing DevExtreme DataGrid in your ASP.NET Core project can significantly enhance your data presentation capabilities. With features like Excel export, advanced filtering, customizable templates, and performance optimizations, you can create powerful and user-friendly data grids that meet your specific needs.

Resources

Here are the official resources we used in preparing this comprehensive guide and recommend for those seeking more information:

  1. ASP.NET Core Official Documentation: https://docs.microsoft.com/en-us/aspnet/core/ Microsoft’s official ASP.NET Core documentation provides in-depth information and best practices about the framework.
  2. DevExtreme ASP.NET Core DataGrid Documentation: https://demos.devexpress.com/aspnetcore/ This page focuses specifically on using DevExtreme DataGrid in ASP.NET Core projects and includes detailed examples.

By referring to these resources, you can access all the information you need to use DevExtreme DataGrid most effectively in your ASP.NET Core projects. These continuously updated documentations will keep you informed about the latest features and best practices.

Yapılan Yorumlar
Bir Yorum Yapın