Tuesday, February 11, 2025
HomeC#Combine ASP.NET Core DataGrid With Boilerplate and Carry out CRUD Actions

Combine ASP.NET Core DataGrid With Boilerplate and Carry out CRUD Actions


TL;DR: Discover ways to combine Syncfusion ASP.NET Core DataGrid into an ASP.NET Boilerplate mission. This weblog walks you thru organising the mission, configuring CRUD operations, and including highly effective information functionalities like filtering, sorting, and looking out. 

ABP (ASP.NET Boilerplate) is an utility framework designed to simplify the event of contemporary internet functions. It incorporates a modular structure and built-in dependency injection, and it helps patterns like Unit of Work and Repository. It consists of computerized API era, multi-tenancy, sturdy authorization and authentication, and localization assist. It additionally offers auditing, logging, and code era instruments and integrates with common UI frameworks like Angular, React, and Blazor, providing a basis for constructing scalable and maintainable apps.

As the online growth panorama evolves, builders consistently search environment friendly and feature-rich options to reinforce their apps. In ASP.NET growth, ASP.NET Boilerplate has emerged as a well-liked framework for constructing sturdy and scalable internet apps.

On this weblog, we’ll discover ways to combine Syncfusion ASP.NET Core DataGrid with ASP.NET Boilerplate framework. 

Create an ASP.NET Boilerplate mission

Step 1: Set up Abp CLI

Make sure the Abp CLI is put in globally in your machine. If not, set up it utilizing the next command.

dotnet software set up -g Volo.Abp.Cli

Step 2: Create a brand new mission

In your most popular folder, create a brand new mission together with your most popular identify utilizing the next command.

abp new SyncfusionGrid -csf

Step 3: Guarantee model compatibility

After efficiently creating the mission, open the answer file. To forestall errors, be sure that the Abp CLI model and all supply mission variations are the identical or decrease than the CLI model. In case your mission Abp bundle model is greater, replace the CLI model by working the next command.

abp cli replace --version x.x.x

Step 4: Configure connection strings

Configure the suitable connection strings within the appsettings.json file for each [projectname].Internet and [projectname].DbMigration initiatives. Afterward, right-click on the DbMigration mission and choose the choice, Set as Begin-up Mission.

[projectname].DbMigration/appsettings.json & [projectname].Internet/appsettings.json

{
  . . .
  "ConnectionStrings": {
    "Default": "Server=XXXXX;Database=SyncfusionGrid;Trusted_Connection=True;TrustServerCertificate=True"
  },
. . .
}

Step 5: Run the mission

Run the mission. It might take a while emigrate the ABP database to your database.

Run the project

Step 6: Configure XSRF-TOKEN

For the reason that POST request is used to name the URL technique within the index.cs web page, we have to configure XSRF-TOKEN and add the next code on the [projectname]WebModule.cs file of the [projectname].Internet mission.

For extra particulars, discuss with the Render Grid in ASP.NET Core Razor Web page?.

[projectname]WebModule.cs

public override void ConfigureServices(ServiceConfigurationContext context)
{
    . . . . . .
    // Want so as to add the codes beneath.
    context.Providers.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}

Moreover, within the Index.cshtml file, add the AntiForgeryToken within the razor web page as follows.

@Html.AntiForgeryToken()

Step 7: Set the online mission as Begin-up

Proper-click on the [projectname].Internet mission and choose Set as Begin-up Mission.

Set up the Syncfusion ASP.NET Core bundle

Let’s begin by putting in the Syncfusion bundle. Proper-click on the [projectname].Internet.csproj file, open Handle NuGet Packages, and seek for Syncfusion.EJ2.AspNet.Core after which set up it.

Alternatively, you need to use the Bundle Supervisor Console. Be sure that the default mission is ready to src/[projectname].Internet of the ASP.NET Boilerplate framework, and run the next command to put in the EJ2 core bundle:

Set up-Bundle Syncfusion.EJ2.AspNet.Core -Model x.x.x

[projectname].Internet.csproj

[projectname].Web.csproj

Add Syncfusion ASP.NET Core Tag Helper

Open the ~/Pages/_ViewImports.cshtml file and add the Syncfusion.EJ2 TagHelper.

~/Pages/_ViewImports.cshtml

@* add Syncfusion.EJ2 TagHelper. *@
@addTagHelper *, Syncfusion.EJ2

Embrace stylesheet and script sources

Within the ~/Pages/Index.cshtml file, add a hyperlink for the EJ2 stylesheet and scripts.

~/Pages/Index.cshtml

<!-- Syncfusion ASP.NET Core controls types -->
<hyperlink rel="stylesheet" href="https://cdn.syncfusion.com/ej2/26.1.40/fluent.css" />
<!-- Syncfusion ASP.NET Core controls scripts -->
<script src="https://cdn.syncfusion.com/ej2/26.1.40/dist/ej2.min.js"></script>

Register Syncfusion Script Supervisor

Register the script supervisor <ejs-script> on the @part scripts of the Razor web page.

~/Pages/Index.cshtml

@part scripts {
    <!-- Syncfusion ASP.NET Core Script Supervisor -->
    <ejs-scripts></ejs-scripts>
}

Troubleshoot: Render Grid rows with out information

By default, ASP.NET Core returns JSON leads to camelCase format, which may additionally alter grid discipline names. To resolve this challenge, we have to add DefaultContractResolver within the Program.cs file.

For this, we have to set up the Microsoft.AspNetCore.Mvc.NewtonsoftJson bundle utilizing the Bundle Supervisor Console or NuGet Bundle Supervisor. 

Program.cs

builder.Providers.AddMvc().AddNewtonsoftJson(choices =>
{
    choices.SerializerSettings.ContractResolver = new DefaultContractResolver();
});

For extra particulars, discuss with the Troubleshooting grid rows with out information.

Including Syncfusion DataGrid

Now, insert the next grid code within the ~/Pages/Index.cshtml file. This instance hyperlinks the information utilizing the customAdaptor idea by extending UrlAdaptor. This method entails sending a put up request to retrieve information from the server and execute extra grid actions.

The Syncfusion ASP.NET Core Grid element helps varied server-side information operations, reminiscent of looking out, sorting, filtering, aggregation, and paging. These operations might be managed utilizing the PerformSearchingPerformFilteringPerformSortingPerformTake, and PerformSkip strategies from the Syncfusion.EJ2.AspNet.Core bundle. Let’s discover find out how to handle these information operations utilizing the UrlAdaptor.

In your API service mission, add the Syncfusion.EJ2.AspNet.Core bundle by the NuGet Bundle Supervisor in Visible Studio (Instruments → NuGet Bundle Supervisor → Handle NuGet Packages for Answer).

To entry DataManagerRequest and QueryableOperation, import the Syncfusion.EJ2.Base in your controller web page.

~/Pages/Index.cshtml

<ejs-grid id="grid" 
          load="onLoad" 
          allowFiltering="true" 
          allowGrouping="true" 
          allowSorting="true" 
          allowPaging="true" 
          toolbar="@(new Record() { 'Add', 'Edit', 'Delete', 'Cancel', 'Replace' })">
    
    <e-grid-editsettings allowEditing="true" 
                         allowAdding="true" 
                         allowDeleting="true">
    </e-grid-editsettings>

    <e-grid-columns>
        <e-grid-column discipline="OrderID" 
                       headerText="Order ID" 
                       isPrimaryKey="true" 
                       textAlign="Proper" 
                       width="120">
        </e-grid-column>

        <e-grid-column discipline="CustomerID" 
                       headerText="Buyer ID" 
                       width="150" 
                       validationRules="@(new { required= true })">
        </e-grid-column>

        <e-grid-column discipline="OrderDate" 
                       headerText="Order Date" 
                       width="130" 
                       textAlign="Proper" 
                       format="yMd">
        </e-grid-column>

        <e-grid-column discipline="Freight" 
                       headerText="Freight" 
                       width="130" 
                       textAlign="Proper" 
                       format="C2" 
                       editType="numericedit" 
                       validationRules="@(new { required= true })">
        </e-grid-column>

        <e-grid-column discipline="ShipCountry" 
                       headerText="Ship Nation" 
                       width="120">
        </e-grid-column>
    </e-grid-columns>

</ejs-grid>

<abp-script src="https://www.syncfusion.com/Pages/Index.js"></abp-script>

Within the ~/Pages/Index.js file, add the next JavaScript code:

window.customAdaptor = new ej.information.UrlAdaptor();
customAdaptor = ej.base.lengthen(customAdaptor, {
    processResponse: operate (information, ds, question, xhr, request, adjustments) {
        request.information = JSON.stringify(information);
        return ej.information.UrlAdaptor.prototype.processResponse.name(this, information, ds, question, xhr, request, adjustments);
    }
});

operate onLoad() {
    this.dataSource = new ej.information.DataManager({
        url: '/Index?handler=GridDataOperationHandler',
        insertUrl: "/Index?handler=GridInsertPostHandler",
        updateUrl: "/Index?handler=GridUpdatePostHandler",
        removeUrl: "/Index?handler=GridRemovePostHandler",
        adaptor: customAdaptor
    });
    this.dataSource.dataSource.headers = [
        { 'XSRF-TOKEN': $("input:hidden[name="__RequestVerificationToken"]").val() }
    ];
}

Dealing with search operations

To implement search performance, guarantee your API endpoint helps customized search standards.  Implement the looking out logic on the server aspect utilizing the PerformSearching technique from the QueryableOperation class. This enables the customized information supply to endure looking out primarily based on the standards specified within the incoming DataManagerRequest object.

In Pages/Index.cshtml.cs file, you’ll be able to handle grid information operations like within the following code instance.

// All information operations besides crud put up.

public JsonResult OnPostGridDataOperationHandler([FromBody] DataManagerRequest dm)
{
    IEnumerable DataSource = orddata.ToList();
    DataOperations operation = new DataOperations();

    if (dm.Search != null && dm.Search.Depend > 0)
    {
        DataSource = operation.PerformSearching(DataSource, dm.Search);  // Search
    }

    return dm.RequiresCounts 
        ? new JsonResult(new { consequence = DataSource, rely = rely }) 
        : new JsonResult(DataSource);
}

Dealing with filtering operations

To deal with filtering operations, be sure that your API endpoint helps customized filtering standards. Implement the filtering logic on the server aspect utilizing the PerformFiltering technique from the QueryableOperation class. This enables the customized information supply to endure filtering primarily based on the standards specified within the incoming DataManagerRequest object.

Pages/Index.cshtml.cs

// All information operations besides crud put up.

public JsonResult OnPostGridDataOperationHandler([FromBody] DataManagerRequest dm)
{
    IEnumerable DataSource = orddata.ToList();
    DataOperations operation = new DataOperations();

    if (dm.The place != null && dm.The place.Depend > 0) // Filtering
    {
        DataSource = operation.PerformFiltering(DataSource, dm.The place, dm.The place[0].Operator);
    }

    return dm.RequiresCounts 
        ? new JsonResult(new { consequence = DataSource, rely = rely }) 
        : new JsonResult(DataSource);
}

Dealing with sorting operations

For sorting operations, be sure that your API endpoint helps customized sorting standards. Implement the sorting logic on the server aspect utilizing the PerformSorting technique from the QueryableOperation class. This enables the customized information supply to endure sorting primarily based on the standards specified within the incoming DataManagerRequest object.

Pages/Index.cshtml.cs

// All information operations besides crud put up.

public JsonResult OnPostGridDataOperationHandler([FromBody] DataManagerRequest dm)
{
    IEnumerable DataSource = orddata.ToList();
    DataOperations operation = new DataOperations();

    if (dm.Sorted != null && dm.Sorted.Depend > 0) // Sorting
    {
        DataSource = operation.PerformSorting(DataSource, dm.Sorted);
    }
    
    int rely = DataSource.Forged().Depend();
    
    if (dm.Skip != 0)
    {
        DataSource = operation.PerformSkip(DataSource, dm.Skip); // Paging
    }
    
    if (dm.Take != 0)
    {
        DataSource = operation.PerformTake(DataSource, dm.Take); // Paging
    }
    
    return dm.RequiresCounts 
        ? new JsonResult(new { consequence = DataSource, rely = rely }) 
        : new JsonResult(DataSource);
}

Dealing with paging operations

For paging, be sure that your API endpoint helps customized paging standards. Implement the paging logic on the server aspect utilizing the PerformTake and PerformSkip strategies from the QueryableOperation class. This enables the customized information supply to endure paging primarily based on the standards specified within the incoming DataManagerRequest object.

Pages/Index.cshtml.cs

// All information operations besides crud put up.

public JsonResult OnPostGridDataOperationHandler([FromBody] DataManagerRequest dm)
{
    IEnumerable DataSource = orddata.ToList();
    DataOperations operation = new DataOperations();
    int rely = DataSource.Forged().Depend();

    if (dm.Skip != 0)
    {
        DataSource = operation.PerformSkip(DataSource, dm.Skip); // Paging
    }
    
    if (dm.Take != 0)
    {
        DataSource = operation.PerformTake(DataSource, dm.Take); // Paging
    }
    
    return dm.RequiresCounts 
        ? new JsonResult(new { consequence = DataSource, rely = rely }) 
        : new JsonResult(DataSource);
}

Dealing with CRUD Operations

The ASP.NET Core DataGrid Part seamlessly integrates CRUD (Create, Learn, Replace, Delete) operations with server-side controller actions by particular properties:  insertUrlremoveUrlupdateUrlcrudUrl, and batchUrl. These properties allow the grid to speak with the information service for each grid motion, facilitating server-side operations.

CRUD operations mapping

CRUD operations inside the grid might be mapped to server-side controller actions utilizing the next particular properties:

  • insertUrl: Specifies the URL for inserting new information.
  • removeUrl: Specifies the URL for eradicating present information.
  • updateUrl: Specifies the URL for updating present information.
  • crudUrl: Specifies a single URL for all CRUD operations.
  • batchUrl: Specifies the URL for batch enhancing.

Insert operation

To insert a brand new document, make the most of the insertUrl property to specify the controller motion mapping URL for the insert operation.

// regular insert put up.
public JsonResult OnPostGridInsertPostHandler([FromBody] CRUDModel worth)
{
    orddata.Insert(0, worth.Worth);
    return new JsonResult(worth);
}

operate onLoad() {
    this.dataSource = new ej.information.DataManager({
        url: '/Index?handler=GridDataOperationHandler',
        insertUrl: "/Index?handler=GridInsertPostHandler",
        // ... different properties
        adaptor: customAdaptor
    });
    // ... extra code
}

Replace operation

To replace present information, make the most of the updateUrl property to specify the controller motion mapping URL for the replace operation.

// regular replace put up.
public JsonResult OnPostGridUpdatePostHandler([FromBody] CRUDModel worth)
{
    var information = orddata.The place(or => or.OrderID == worth.Worth.OrderID).FirstOrDefault();
    if (information != null)
    {
        information.OrderID = worth.Worth.OrderID;
        information.CustomerID = worth.Worth.CustomerID;
        information.Freight = worth.Worth.Freight;
        information.EmployeeID = worth.Worth.EmployeeID;
        information.ShipCity = worth.Worth.ShipCity;
        information.Verified = worth.Worth.Verified;
        information.OrderDate = worth.Worth.OrderDate;
        information.ShipName = worth.Worth.ShipName;
        information.ShipCountry = worth.Worth.ShipCountry;
        information.ShippedDate = worth.Worth.ShippedDate;
        information.ShipAddress = worth.Worth.ShipAddress;
    }
    return new JsonResult(worth);
}

operate onLoad() {
    this.dataSource = new ej.information.DataManager({
        // ... different properties
        updateUrl: "/Index?handler=GridUpdatePostHandler",
        // ... extra code
        adaptor: customAdaptor
    });
    // ... extra code
}

Delete operation

To delete present information, use the removeUrl property to specify the controller motion mapping URL for the delete operation

In Pages/Index.cshtml.cs, you’ll be able to carry out grid information operations as follows:

// regular delete put up.
public JsonResult OnPostGridRemovePostHandler([FromBody] CRUDModel worth)
{
    orddata.Take away(orddata.The place(or => or.OrderID == (Int64)worth.Key).FirstOrDefault());
    return new JsonResult(worth);
}

operate onLoad() {
    this.dataSource = new ej.information.DataManager({
        // ... different properties
        removeUrl: "/Index?handler=GridRemovePostHandler",
        adaptor: customAdaptor
    });
    // ... extra code
}

A single technique for performing all CRUD operations

Utilizing the crudUrl property, the controller motion mapping URL might be specified to carry out all of the CRUD operations on the server aspect utilizing a single technique as an alternative of defining separate controller motion strategies for CRUD (insert, replace, and delete) operations.

Seek advice from the next code instance.

~/Pages/Index.js

window.customAdaptor = new ej.information.UrlAdaptor();

customAdaptor = ej.base.lengthen(customAdaptor, {
    processResponse: operate (information, ds, question, xhr, request, adjustments) {
        request.information = JSON.stringify(information);
        return ej.information.UrlAdaptor.prototype.processResponse.name(this, information, ds, question, xhr, request, adjustments);
    }
});

operate onLoad() {
    this.dataSource = new ej.information.DataManager({
        url: '/Index?handler=GridDataOperationHandler',
        crudUrl: "/Index?handler=GridCrudPostHandler", // add solely crud url right here.
        adaptor: customAdaptor
    });
    this.dataSource.dataSource.headers = [{ 'XSRF-TOKEN': $("input:hidden[name="__RequestVerificationToken"]").val() }];
}

~/Pages/Index.cshtml.cs

// regular edit crud url put up.
public JsonResult OnPostGridCrudPostHandler([FromBody] CRUDModel<OrdersDetails> worth)
{
    // regular replace put up.
    if (worth.Motion == "replace")
    {
        var information = orddata.The place(or => or.OrderID == worth.Worth.OrderID).FirstOrDefault();
        if (information != null)
        {
            information.OrderID = worth.Worth.OrderID;
            information.CustomerID = worth.Worth.CustomerID;
            information.Freight = worth.Worth.Freight;
            information.EmployeeID = worth.Worth.EmployeeID;
            information.ShipCity = worth.Worth.ShipCity;
            information.Verified = worth.Worth.Verified;
            information.OrderDate = worth.Worth.OrderDate;
            information.ShipName = worth.Worth.ShipName;
            information.ShipCountry = worth.Worth.ShipCountry;
            information.ShippedDate = worth.Worth.ShippedDate;
            information.ShipAddress = worth.Worth.ShipAddress;
        }
    }
    // regular insert put up.
    else if (worth.Motion == "insert")
    {
        orddata.Insert(0, worth.Worth);
    }
    // regular delete put up.
    else if (worth.Motion == "take away")
    {
        orddata.Take away(orddata.The place(or => or.OrderID == (Int64)worth.Key).FirstOrDefault());
    }
    
    return new JsonResult(worth);
}

Dealing with batch/bulk CRUD operations

To carry out batch operation, outline the edit mode as Batch and specify the batchUrl property within the DataManager. Use the add toolbar button to insert a brand new row in batch enhancing mode. To edit a cell, double-click the specified cell and replace the worth as required. To delete a document, choose the document and press the delete toolbar button. Now, all CRUD operations might be executed in a single request.

~/Pages/Index.cshtml

<ejs-grid id="grid" load="onLoad" allowFiltering="true" allowGrouping="true" allowSorting="true" allowPaging="true" toolbar="@(new Record<string>() { "Add", "Edit", "Delete", "Cancel", "Replace" })">
    // want so as to add batch mode.
    <e-grid-editsettings allowEditing="true" allowAdding="true" allowDeleting="true" mode="Batch"></e-grid-editsettings>
    . . . . . .
</ejs-grid>
<abp-script src="https://www.syncfusion.com/Pages/Index.js" />

~/Pages/Index.js

// . . . . . . .

operate onLoad() {
    this.dataSource = new ej.information.DataManager({
        url: '/Index?handler=GridDataOperationHandler',
        batchUrl: "/Index?handler=GridBatchCrudPostHandler", // add solely batch crud url right here.
        adaptor: customAdaptor
    });
    this.dataSource.dataSource.headers = [{ 'XSRF-TOKEN': $("input:hidden[name="__RequestVerificationToken"]").val() }];
}

~/Pages/Index.cshtml.cs

// Batch edit bulk crud url put up.

public JsonResult OnPostGridBatchCrudPostHandler([FromBody] CRUDModel<OrdersDetails> worth)
{
    if (worth.Modified.Depend > 0)
    {
        for (int i = 0; i < worth.Modified.Depend; i++)
        {
            var information = orddata.The place(or => or.OrderID == worth.Modified[i].OrderID).FirstOrDefault();
            if (information != null)
            {
                information.OrderID = worth.Modified[i].OrderID;
                information.CustomerID = worth.Modified[i].CustomerID;
                information.Freight = worth.Modified[i].Freight;
                information.EmployeeID = worth.Modified[i].EmployeeID;
                information.ShipCity = worth.Modified[i].ShipCity;
                information.Verified = worth.Modified[i].Verified;
                information.OrderDate = worth.Modified[i].OrderDate;
                information.ShipName = worth.Modified[i].ShipName;
                information.ShipCountry = worth.Modified[i].ShipCountry;
                information.ShippedDate = worth.Modified[i].ShippedDate;
                information.ShipAddress = worth.Modified[i].ShipAddress;
            }
        }
    }
    if (worth.Added.Depend > 0)
    {
        for (var i = 0; i < worth.Added.Depend; i++)
        {
            orddata.Insert(i, worth.Added[i]);
        }
    }
    if (worth.Deleted.Depend > 0)
    {
        for (var i = 0; i < worth.Deleted.Depend; i++)
        {
            orddata.Take away(orddata.The place(or => or.OrderID == worth.Deleted[i].OrderID).FirstOrDefault());
        }
    }
    return new JsonResult(worth);
}

Seek advice from the next picture.

Integrating ASP.NET Core DataGrid in Boilerplate and performing CRUD actions
Integrating ASP.NET Core DataGrid in Boilerplate and performing CRUD actions

GitHub reference

For extra particulars, discuss with the integrating ASP.NET Core DataGrid in ASP.NET Boilerplate GitHub demo.

Conclusion

Thanks for studying! In conclusion, integrating Syncfusion ASP.NET Core DataGrid with ASP.NET Boilerplate offers builders with a potent mixture for constructing sturdy and scalable internet apps. By harnessing the capabilities of the DataGrid, builders can streamline their growth workflows and ship compelling consumer experiences.

All through this exploration, we’ve witnessed how our DataGrid serves as a cornerstone for displaying and managing tabular information successfully inside ASP.NET Boilerplate apps. 

For present prospects, the brand new model of Important Studio® is out there for obtain from the License and Downloads web page. In case you are not a Syncfusion buyer, strive our 30-day free trial to take a look at our out there options.

You’ll be able to contact us by our assist discussion boardassist portal, or suggestions portal. We’re right here that can assist you succeed!

Associated blogs

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments