From c57d13294893ed707ddefd8511d08e24a0cce91d Mon Sep 17 00:00:00 2001 From: SadhanaBaskaran Date: Fri, 5 Dec 2025 19:27:06 +0530 Subject: [PATCH] 992126: Updated the UG content and samples for ForeignKey Column in Blazor DataGrid --- blazor/datagrid/foreignKey-column.md | 558 ++++++--------------------- 1 file changed, 115 insertions(+), 443 deletions(-) diff --git a/blazor/datagrid/foreignKey-column.md b/blazor/datagrid/foreignKey-column.md index fe69ebc23a..48d30f26fd 100644 --- a/blazor/datagrid/foreignKey-column.md +++ b/blazor/datagrid/foreignKey-column.md @@ -1,7 +1,7 @@ --- layout: post title: Foreign key column in Blazor DataGrid Component | Syncfusion -description: Checkout and learn here all about Foreign key column in the Syncfusion Blazor DataGrid component and much more details. +description: Learn how to configure and customize foreign key columns in Syncfusion Blazor DataGrid, including remote data binding and edit templates. platform: Blazor control: DataGrid documentation: ug @@ -9,21 +9,17 @@ documentation: ug # Foreign key column in Blazor DataGrid -The Foreign key column in the Syncfusion® Blazor DataGrid allows you to display related data from a foreign key data source in a column within the Grid. This feature is particularly useful when you have a column in the Grid that represents a foreign key relationship with another data source. +The Syncfusion® Blazor DataGrid supports displaying related data from a **foreign key data source** in a column. This feature is useful when a column represents a foreign key relationship with another data source. -Foreign key column can be enabled by using `ForeignDataSource`, [ForeignKeyField](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyField) and [ForeignKeyValue](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyValue) properties of **GridForeignColumn** directive. +A foreign key column can be configured using the following properties of the [GridForeignColumn](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridForeignColumn-1.html) directive: -Define the foreign key column in the Grid using the following properties: - -* `ForeignDataSource` - Specifies the foreign data source that contains the related data. -* [ForeignKeyField](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyField) - Maps the column name in the Grid to the field in the foreign data source that represents the foreign key relationship. -* [ForeignKeyValue](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyValue) -Specifies the field from the foreign data source that should be displayed in the Grid as the related data. +* [ForeignDataSource](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridForeignColumn-1.html#Syncfusion_Blazor_Grids_GridForeignColumn_1_ForeignDataSource) – Specifies the data source that contains the related data. +* [ForeignKeyField](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyField) – Maps the column in the Grid to the field in the foreign data source that represents the foreign key. +* [ForeignKeyValue](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyValue) – Specifies the field from the foreign data source that should be displayed in the Grid. ## Binding local data -The Syncfusion® Blazor DataGrid provides a convenient way to bind local data to a foreign key column. This allows you to display related data from a local data source within the Grid. Here’s an example of how to bind local data to a Foreign Key column in Grid: - -In this example, data is the local data source for the Grid, and **Employee Name** is the local data source for the foreign key column. The ForeignKeyValue property is set to **FirstName** which represents the field name in the **Employee Name** that you want to display in the foreign key column. +The Syncfusion® Blazor DataGrid supports binding local data to a foreign key column. This allows related data from a local data source to be displayed within the Grid. {% tabs %} {% highlight razor tabtitle="Index.razor" %} @@ -119,9 +115,7 @@ public class EmployeeDetails ## Binding remote data -The Foreign key column in Syncfusion® Blazor DataGrid allows you to bind remote data for a foreign key column. You can use `SfDataManager` instead of using `DataSource` property. - -This example demonstrates how to use the foreign key column with remote data binding using the `ODataV4Adaptor` in the Grid: +The Syncfusion® Blazor DataGrid supports binding remote data to a foreign key column using [SfDataManager](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Data.SfDataManager.html). This approach is useful when retrieving data from services such as **OData**, **Web API**, or other remote endpoints. {% tabs %} {% highlight razor tabtitle="Index.razor" %} @@ -199,14 +193,13 @@ public class OrderDetails ![Foreign key column with remote data](./images/foreignkey-remote-data.png) -> * For remote data, the sorting and grouping is done based on [ForeignKeyField](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyField) instead of [ForeignKeyValue](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyValue). -> * If [ForeignKeyField](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyField) is not defined, then the column uses [Field](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_Field) property of **GridColumn** tag helper. +> * For remote data, **sorting** and **grouping** operations are performed based on the [ForeignKeyField](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyField) property rather than the [ForeignKeyValue](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyValue) property. -## Use edit template in foreign key column +> * If `ForeignKeyField` is not defined, the column uses the [Field](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_Field) property of the [GridColumn](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html) directive. -The Syncfusion® Blazor DataGrid provides support for using an edit template in a foreign key column. By default, a dropdown is used for editing foreign key column. Other editable components can be rendered using the `EditTemplate` feature of Grid. The following example demonstrates the way of using edit template with `ComboBox` in the foreign column. +## Use edit template in foreign key column -In the following code example, the Employee Name is a foreign key column. When editing, the `ComboBox` is rendered instead of `DropDownList`: +The Syncfusion® Blazor DataGrid supports customizing the editor for a foreign key column using the [EditTemplate](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_EditTemplate) feature. By default, a [dropdown](https://blazor.syncfusion.com/documentation/dropdown-list/getting-started-with-web-app) is rendered for editing foreign key columns. Other components, such as [ComboBox](https://blazor.syncfusion.com/documentation/combobox/getting-started-with-web-app), can be used by defining an edit template. {% tabs %} {% highlight razor tabtitle="Index.razor" %} @@ -323,11 +316,11 @@ In the following code example, the Employee Name is a foreign key column. When e ## Customize filter UI in foreign key column -The Syncfusion® Blazor DataGrid allows you to customize the filtering user interface (UI) for foreign key columns by using the [FilterTemplate](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_FilterTemplate) property. By default, a dropdown is used for filtering foreign key columns. However, you can create your own custom filtering UI by [FilterTemplate](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_FilterTemplate) property. Here’s an example that demonstrates how to create a custom filtering UI in a foreign key column: +The Syncfusion® Blazor DataGrid allows customizing the filtering interface for foreign key columns using the [FilterTemplate](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_FilterTemplate) property. By default, a dropdown is rendered for filtering foreign key columns. The `FilterTemplate` property enables creating a custom UI for filtering. -> For all filter types other than FilterBar, filtering parameters will be sent in the form of `PredicateModel`. Here, T represents the type of `ForeignKeyValue` property when using the foreign key column. +> For all filter types other than `FilterBar`, filtering parameters are passed as **PredicateModel**, where **T** represents the type of the [ForeignKeyValue](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_ForeignKeyValue) property when using a foreign key column. -In this example, a `DropDownList` is rendered as the filter UI for the **“EmployeeID”** foreign key column. The **DataSource** property of the `SfDropDownList` is set to the employees data, and the Fields property is configured to display the **FirstName** field as the text and **EmployeeID** field as the value. The `value` property is set to the current filter value of the column. +In this configuration, a [DropDownList](https://blazor.syncfusion.com/documentation/dropdown-list/getting-started-with-web-app) is rendered as the filter UI for the **EmployeeID** foreign key column. The [DataSource](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.DropDowns.SfDropDownBase-1.html#Syncfusion_Blazor_DropDowns_SfDropDownBase_1_DataSource) property of `SfDropDownList` is set to the **employees** collection, and the `Fields` property maps **FirstName** as the **display text** and **EmployeeID** as the **value**. The `Value` property is bound to the current filter value of the column. {% tabs %} {% highlight razor tabtitle="Index.razor" %} @@ -433,9 +426,7 @@ public class EmployeeDetails ## Use filter bar template in foreign key column -You can use the filter template in a foreign key column in Syncfusion® Blazor DataGrid by using the [FilterTemplate](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_FilterTemplate) property. This allows you to customize the filter bar for the foreign key column with a custom component or HTML template. Here’s an example that demonstrates how to use a Filter template in a foreign key column: - -In this example, the **“EmployeeID”** column is a foreign key column. The `FilterTemplate` property is used to render a `DropDownList` as a filter, you can select filter value by using the **DropDown** options. +The Syncfusion® Blazor DataGrid allows customizing the filter bar for foreign key columns using the [FilterTemplate](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_FilterTemplate) property. This feature enables rendering a custom component or HTML template in the filter bar instead of the default UI. {% tabs %} {% highlight razor tabtitle="Index.razor" %} @@ -567,17 +558,13 @@ public class EmployeeDetails ## Perform aggregation in foreign key column -By default, aggregations are not supported in a foreign key column in the Syncfusion® Blazor DataGrid. However, you can achieve aggregation for a foreign key column by using `customAggregate`. +By default, the Syncfusion® Blazor DataGrid does not support aggregation in foreign key columns. However, this can be achieved by using a custom aggregate function. -To perform aggregation in a foreign key column, follow these steps: +To perform aggregation in a foreign key column: 1. Define a foreign key column in the Grid. -2. Implement a custom aggregate function to calculate the aggregation for the foreign key column. -3. Set the `customAggregate` property of the column to the custom aggregate function. - -Here's an example that demonstrates how to perform aggregation in a foreign key column: - -In the provided example, the `customAggregateFn` function is used to filter and count the **Margaret** data based on the **FirstName** field of the foreign key column. The result is displayed in the Grid's footer template using the [FooterTemplate](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridAggregateColumn.html#Syncfusion_Blazor_Grids_GridAggregateColumn_FooterTemplate) property. +2. Implement a custom aggregate function to calculate the required value. +3. Assign the function to the `CustomAggregate` property of the aggregate column. {% tabs %} {% highlight razor tabtitle="Index.razor" %} @@ -690,83 +677,102 @@ public class EmployeeDetails ## Prevent filter query generation for foreign key column -By default, a filter query for the foreign key column will be generated based on the foreign key value. You can prevent the default filter query generation for the foreign key column and add the custom filter query. This can be achieved by setting the [PreventFilterQuery](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.ActionEventArgs-1.html#Syncfusion_Blazor_Grids_ActionEventArgs_1_PreventFilterQuery) argument of the [OnActionBegin](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridEvents-1.html#Syncfusion_Blazor_Grids_GridEvents_1_OnActionBegin) event to true. - -In the following code sample, you can prevent default filter query generation using the `PreventFilterQuery` property and generate a custom filter query to execute a filter operation: +By default, the DataGrid generates a filter query for foreign key columns based on the foreign key value. To override this behavior and apply a custom filter query, use the [Filtering](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridEvents-1.html#Syncfusion_Blazor_Grids_GridEvents_1_Filtering) event and set the [PreventFilterQuery](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.FilteringEventArgs.html#Syncfusion_Blazor_Grids_FilteringEventArgs_PreventFilterQuery) property to **true**. Then, define a custom query using the `Query` class. {% tabs %} {% highlight razor tabtitle="Index.razor" %} -@using System.ComponentModel.DataAnnotations; + +@using Syncfusion.Blazor @using Syncfusion.Blazor.Data @using Syncfusion.Blazor.Grids -@using Syncfusion.Blazor.DropDowns -@using Newtonsoft.Json - - - - - + + + + + + - - - + + + + - - + + -@code{ - SfGrid Grid { get; set; } + + +@code { + private SfGrid Grid { get; set; } private Query currentQuery = new Query(); - public List ToolbarItems = new List() { "Add", "Edit", "Delete", "Update", "Cancel", "Search" }; - - private void OnActionBegin(Syncfusion.Blazor.Grids.ActionEventArgs args) - { - if (args.RequestType == Syncfusion.Blazor.Grids.Action.Filtering) + public List ToolbarItems = new() { "Search" }; + + private void FilteringHandler(Syncfusion.Blazor.Grids.FilteringEventArgs args) + { + if (!string.Equals(args.ColumnName, nameof(OrderDto.EmployeeID), StringComparison.OrdinalIgnoreCase)) { - if (String.Equals(args.CurrentFilteringColumn, nameof(Book.CustomerId), StringComparison.OrdinalIgnoreCase)) - { - args.PreventFilterQuery = true; - currentQuery = new Query().Where("Customer/Name", args.CurrentFilterObject.Operator.ToString().ToLower(), args.CurrentFilterObject.Value, true, true); - } + return; + } + + args.PreventFilterQuery = true; + + if (args.FilterPredicates is null || args.FilterPredicates.Count == 0) + { + currentQuery = new Query(); + return; + } + + currentQuery = new Query(); + foreach (var p in args.FilterPredicates) + { + const string navigationField = "Employee/FirstName"; + var op = p.Operator.ToString()?.ToLowerInvariant(); + if (string.IsNullOrWhiteSpace(op)) continue; + + var value = p.Value ?? p.ActualValue; + var caseInsensitive = p.MatchCase == false; + var ignoreAccent = p.IgnoreAccent; + + currentQuery = currentQuery.Where(navigationField, op, value, caseInsensitive, ignoreAccent); } } - public class Book + public class OrderDto { - [Key] - public Guid Id { get; set; } - public Guid CustomerId { get; set; } - public Guid CustomerId1 { get; set; } - public virtual Customer Customer { get; set; } - public int CreditLimit { get; set; } - public bool Active { get; set; } - public bool IsDeleted { get; set; } + public int OrderID { get; set; } + public string CustomerID { get; set; } + public int EmployeeID { get; set; } + public DateTime? OrderDate { get; set; } + public string ShipCountry { get; set; } } - public class Customer + public class EmployeeDto { - [Key] - public Guid Id { get; set; } - public string Name { get; set; } - [JsonIgnore] - public List CustomerBooks { get; set; } + public int EmployeeID { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string Title { get; set; } + public string City { get; set; } + public string Country { get; set; } } } + {% endhighlight %} {% endtabs %} -{% previewsample "https://blazorplayground.syncfusion.com/embed/BZrzXrWOrKYCkblp?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %} - ## Render foreign key value in column template -The Syncfusion® Blazor DataGrid supports rendering foreign key values within a column template, allowing for a more meaningful display of related data. Instead of showing the underlying foreign key value, you can customize the column to display a corresponding descriptive value from a related data source. - -To achieve this, define a column using the [Template](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_Template) property and use the foreign key mapping to bind and render the desired value. This approach is especially useful when the foreign key refers to an ID and you want to display the corresponding name or label. +The Syncfusion® Blazor DataGrid supports rendering foreign key values within a [column template](https://blazor.syncfusion.com/documentation/datagrid/column-template), enabling display of descriptive values from a related data source instead of the underlying foreign key. This approach is useful when a foreign key refers to an ID and a corresponding name or label needs to be shown. -The following example demonstrates how to render a foreign key value using a column template in the Grid: +To configure this feature, define a column using the [Template](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_Template) property and bind the required value from the foreign key mapping. {% tabs %} {% highlight razor tabtitle="Index.razor" %} @@ -856,9 +862,7 @@ The following example demonstrates how to render a foreign key value using a col ## Enable multiple foreign key columns -The Syncfusion® Blazor DataGrid supports the feature of enabling multiple foreign key columns with editing options. This allows users to display columns from foreign data sources in the Grid. - -In the following example, Employee Name and Ship City are foreign key columns that display the FirstName and ShipCity columns from foreign data: +The Syncfusion® Blazor DataGrid supports configuring multiple foreign key columns with editing options. This feature allows displaying related data from different foreign data sources in the Grid. {% tabs %} {% highlight razor tabtitle="Index.razor" %} @@ -991,350 +995,17 @@ public class EmployeeDetails {% previewsample "https://blazorplayground.syncfusion.com/embed/BNBJCLZnLheGLept?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %} -> You can find the fully working sample [here](https://github.com/SyncfusionExamples/blazor-datagrid-prevent-query-generation-for-foriegnkey-column). - ## Edit template in foreign key column using remote data -The Syncfusion® Blazor DataGrid allows you to customize the edit template for foreign key columns when using remote data. By default, a [DropDownList](https://blazor.syncfusion.com/documentation/dropdown-list/getting-started-with-web-app) is used for editing foreign key column. Other editable components can be rendered using the edit template feature of Grid. - -This example demonstrates how to use an edit template in a foreign key column with remote data. In this case, an [AutoComplete](https://blazor.syncfusion.com/documentation/autocomplete/getting-started-with-web-app) is rendered as the edit template for the **EmployeeID** foreign key column. You can use `SfDataManager` instead of the `DataSource` property to bind remote data. Follow the steps below to achieve this: - -**1. Create a Blazor web app** - -You can create a **Blazor Web App** named **EditTemplate** using Visual Studio 2022, either via [Microsoft Templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-8.0) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio). Make sure to configure the appropriate [interactive render mode](https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-8.0#render-modes) and [interactivity location](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-8.0&pivots=windows). - -**2. Install Syncfusion® Blazor DataGrid, AutoComplete, and Themes NuGet Packages** - -To add the `Grid` and `AutoComplete` in the app, open the NuGet Package Manager in Visual Studio (*Tools → NuGet Package Manager → Manage NuGet Packages for Solution*), search and install [Syncfusion.Blazor.Grid](https://www.nuget.org/packages/Syncfusion.Blazor.Grid/), [Syncfusion.Blazor.DropDowns](https://www.nuget.org/packages/Syncfusion.Blazor.DropDowns), and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/). - -If your Blazor Web App uses `WebAssembly` or `Auto` render modes, install the Syncfusion® Blazor NuGet packages in the client project. - -Alternatively, use the following Package Manager commands: - -```powershell -Install-Package Syncfusion.Blazor.Grid -Version {{ site.releaseversion }} -Install-Package Syncfusion.Blazor.Themes -Version {{ site.releaseversion }} -Install-Package Syncfusion.Blazor.DropDowns -Version {{ site.releaseversion }} -``` - -> Syncfusion® Blazor components are available on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to the [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for a complete list of available packages. - -**3. Register Syncfusion® Blazor service** - -- Open the **~/_Imports.razor** file and import the required namespaces. - -```csharp -@using Syncfusion.Blazor -@using Syncfusion.Blazor.Grids -@using Syncfusion.Blazor.DropDowns -``` - -- Register the Syncfusion® Blazor service in the **~/Program.cs** file. - -```csharp -using Syncfusion.Blazor; - -builder.Services.AddSyncfusionBlazor(); -``` - -For apps using `WebAssembly` or `Auto (Server and WebAssembly)` render modes, register the service in both **~/Program.cs** files. - -**4. Add stylesheet and script resources** - -Include the theme stylesheet and script references in the **~/Components/App.razor** file. - -```html - - .... - - -.... - - .... - - -``` - -> * Refer to the [Blazor Themes](https://blazor.syncfusion.com/documentation/appearance/themes) topic for various methods to include themes (e.g., Static Web Assets, CDN, or CRG). -> * Set the render mode to **InteractiveServer** or **InteractiveAuto** in your Blazor Web App configuration. - -**5. Register controllers in `Program.cs`** - -Add the following lines in the `Program.cs` file to register controllers: - -```csharp -// Register controllers in the service container. -builder.Services.AddControllers(); - -// Map controller routes. -app.MapControllers(); -``` - -**6. Create a model class** - -Create a new folder named **Models**. Inside this folder, add a model class named **OrdersDetails.cs** to represent the order data, and another model class named **EmployeeData.cs** to represent the employee data. - -{% tabs %} -{% highlight cs tabtitle="GridController.cs" %} - -namespace EditTemplate.Models -{ - public class OrdersDetails - { - private static List order = new List(); - public OrdersDetails() { } - - public OrdersDetails(int OrderID, string CustomerID, int EmployeeID, string ShipName, string ShipCountry) - { - this.OrderID = OrderID; - this.CustomerID = CustomerID; - this.EmployeeID = EmployeeID; - this.ShipName = ShipName; - this.ShipCountry = ShipCountry; - } - - public static List GetAllRecords() - { - if (order.Count == 0) - { - order.Add(new OrdersDetails(1, "ALFKI", 1, "Simons Bistro", "Denmark")); - order.Add(new OrdersDetails(2, "ANATR", 2, "Queen Cozinha", "Brazil")); - order.Add(new OrdersDetails(3, "ANTON", 3, "Frankenversand", "Germany")); - order.Add(new OrdersDetails(4, "BLONP", 4, "Ernst Handel", "Austria")); - order.Add(new OrdersDetails(5, "BOLID", 5, "Hanari Carnes", "Switzerland")); - order.Add(new OrdersDetails(6, "ALFKI", 6, "Smith Foods", "UK")); - order.Add(new OrdersDetails(7, "ANATR", 7, "La Cuisine", "France")); - order.Add(new OrdersDetails(8, "ANTON", 8, "Gourmet Market", "USA")); - order.Add(new OrdersDetails(9, "BLONP", 9, "Pasta Supremo", "Italy")); - order.Add(new OrdersDetails(10, "BOLID", 10, "Frankenversand", "Germany")); - } - return order; - } - - public int? OrderID { get; set; } - public string? CustomerID { get; set; } - public int? EmployeeID { get; set; } - public string? ShipName { get; set; } - public string? ShipCountry { get; set; } - } -} - -{% endhighlight %} - -{% highlight cs tabtitle="EmployeeData.cs" %} - -namespace EditTemplate.Models -{ - public class EmployeeData - { - public int? EmployeeID { get; set; } - public string? FirstName { get; set; } - public string? LastName { get; set; } - public string? Department { get; set; } - public string? Email { get; set; } - public string? PhoneNumber { get; set; } - - public static List GetAllRecords() - { - return new List - { - new EmployeeData { EmployeeID = 1, FirstName = "John", LastName = "Doe", Department = "Sales", Email = "john.doe@example.com", PhoneNumber = "123-456-7890" }, - new EmployeeData { EmployeeID = 2, FirstName = "David", LastName = "Smith", Department = "Marketing", Email = "david.smith@example.com", PhoneNumber = "987-654-3210" }, - new EmployeeData { EmployeeID = 3, FirstName = "Maria", LastName = "Gonzalez", Department = "HR", Email = "maria.gonzalez@example.com", PhoneNumber = "456-789-0123" }, - new EmployeeData { EmployeeID = 4, FirstName = "Sophia", LastName = "Brown", Department = "Finance", Email = "sophia.brown@example.com", PhoneNumber = "321-654-0987" }, - new EmployeeData { EmployeeID = 5, FirstName = "James", LastName = "Wilson", Department = "IT", Email = "james.wilson@example.com", PhoneNumber = "654-321-7654" }, - new EmployeeData { EmployeeID = 6, FirstName = "Emma", LastName = "Taylor", Department = "Operations", Email = "emma.taylor@example.com", PhoneNumber = "213-546-8790" }, - new EmployeeData { EmployeeID = 7, FirstName = "Daniel", LastName = "Anderson", Department = "Logistics", Email = "daniel.anderson@example.com", PhoneNumber = "789-654-3210" }, - new EmployeeData { EmployeeID = 8, FirstName = "Olivia", LastName = "Thomas", Department = "Procurement", Email = "olivia.thomas@example.com", PhoneNumber = "567-890-1234" }, - new EmployeeData { EmployeeID = 9, FirstName = "Michael", LastName = "Harris", Department = "R&D", Email = "michael.harris@example.com", PhoneNumber = "890-123-4567" }, - new EmployeeData { EmployeeID = 10, FirstName = "Lucas", LastName = "Martin", Department = "Customer Service", Email = "lucas.martin@example.com", PhoneNumber = "345-678-9012" }, - }; - } - } -} - -{% endhighlight %} -{% endtabs %} +The Syncfusion® Blazor DataGrid supports customizing the edit template for foreign key columns when using remote data. By default, a [DropDownList](https://blazor.syncfusion.com/documentation/dropdown-list/getting-started-with-web-app) is rendered for editing. Other components, such as [AutoComplete](https://blazor.syncfusion.com/documentation/autocomplete/getting-started-with-web-app), can be used by defining an [EditTemplate](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_EditTemplate). -**7. Create an API controller** +**Key steps** -Create an API controller (aka, **GridController.cs and EmployeesController.cs**) file under **Controllers** folder that helps to establish data communication with the Grid. +1. Configure [SfDataManager](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Data.SfDataManager.html) in the Grid for remote **CRUD** operations using [UrlAdaptor](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Adaptors.html#Syncfusion_Blazor_Adaptors_UrlAdaptor). +2. Render `SfDataManager` inside the foreign key column for remote foreign data. +3. Use `EditTemplate` to render a custom component like [SfAutoComplete](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.DropDowns.SfAutoComplete-2.html), bind the foreign key field using [@bind-Value](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.DropDowns.SfDropDownList-2.html#Syncfusion_Blazor_DropDowns_SfDropDownList_2_Value), and configure [AutoCompleteFieldSettings](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.DropDowns.AutoCompleteFieldSettings.html) with [Text](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.DropDowns.AutoCompleteFieldSettings.html#Syncfusion_Blazor_DropDowns_AutoCompleteFieldSettings_Text) and [Value](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.DropDowns.AutoCompleteFieldSettings.html#Syncfusion_Blazor_DropDowns_AutoCompleteFieldSettings_Value). - * The **GetOrderData** method retrieves sample order data. Replace it with your custom logic to fetch data from a database or other sources. - * The **GetEmployeeDetails** method retrieves sample employee data. Replace it with your custom logic to fetch data from a database or other sources. - -{% tabs %} -{% highlight cs tabtitle="GridController.cs" %} - -using EditTemplate.Models; -using Microsoft.AspNetCore.Mvc; -using Syncfusion.Blazor; -using Syncfusion.Blazor.Data; - -namespace EditTemplate.Controllers -{ - [ApiController] - [Route("api/[controller]")] - public class GridController : ControllerBase - { - /// - /// Retrieves the list of orders. - /// - /// Retrieve data from the data source. - [HttpGet] - public List GetOrdersDetails() - { - return OrdersDetails.GetAllRecords().ToList(); - } - - /// - /// Handles server-side paging and returns the processed data. - /// - /// Returns the paged data and total record count in result and count format. - [HttpPost] - public object Post([FromBody] DataManagerRequest DataManagerRequest) - { - // Retrieve data source and convert to queryable. - IQueryable DataSource = GetOrdersDetails().AsQueryable(); - - // Get the total records count. - int totalRecordsCount = DataSource.Count(); - - // Handling Paging in UrlAdaptor. - if (DataManagerRequest.Skip != 0) - { - DataSource = DataOperations.PerformSkip(DataSource, DataManagerRequest.Skip); - //Add custom logic here if needed and remove above method. - } - if (DataManagerRequest.Take != 0) - { - DataSource = DataOperations.PerformTake(DataSource, DataManagerRequest.Take); - //Add custom logic here if needed and remove above method. - } - // Get total records count. - int totalRecordsCount = DataSource.Count(); - - // Return data and count. - return new { result = DataSource, count = totalRecordsCount }; - } - - /// - /// Inserts a new data item into the data collection. - /// - /// It contains the new record detail which is need to be inserted. - /// Returns void. - [HttpPost("Insert")] - public void Insert([FromBody] CRUDModel newRecord) - { - if (newRecord.value != null) - { - // Add the new record to the data collection. - OrdersDetails.GetAllRecords().Insert(0, newRecord.value); - } - } - - /// - /// Update a existing data item from the data collection. - /// - /// It contains the updated record detail which is need to be updated. - /// Returns void. - [HttpPost("Update")] - public void Update([FromBody] CRUDModel updatedRecord) - { - var updatedOrder = updatedRecord.value; - if (updatedOrder != null) - { - var data = OrdersDetails.GetAllRecords().FirstOrDefault(or => or.OrderID == updatedOrder.OrderID); - if (data != null) - { - // Update the existing record. - data.OrderID = updatedOrder.OrderID; - data.CustomerID = updatedOrder.CustomerID; - data.EmployeeID = updatedOrder.EmployeeID; - data.ShipCountry = updatedOrder.ShipCountry; - // Update other properties similarly. - } - } - } - - /// - /// Remove a specific data item from the data collection. - /// - /// It contains the specific record detail which is need to be removed. - /// Returns void. - [HttpPost("Remove")] - public void Remove([FromBody] CRUDModel deletedRecord) - { - // Get the key value from the deletedRecord. - int orderId = int.Parse(deletedRecord.key.ToString()); - var data = OrdersDetails.GetAllRecords().FirstOrDefault(OrdersDetails => OrdersDetails.OrderID == orderId); - if (data != null) - { - // Remove the record from the data collection. - OrdersDetails.GetAllRecords().Remove(data); - } - } - - public class CRUDModel where T : class - { - public string? action { get; set; } - public string? keyColumn { get; set; } - public object? key { get; set; } - public T? value { get; set; } - public List? added { get; set; } - public List? changed { get; set; } - public List? deleted { get; set; } - public IDictionary? @params { get; set; } - } - } -} - -{% endhighlight %} - -{% highlight cs tabtitle="EmployeesController.cs" %} - -using EditTemplate.Models; -using Microsoft.AspNetCore.Mvc; -using Syncfusion.Blazor; - -namespace EditTemplate.Controllers -{ - [ApiController] - public class EmployeesController : ControllerBase - { - /// - /// Retrieves all employee data from the data source. - /// - /// Returns the full list of employee data. - [HttpGet] - [Route("api/[controller]")] - public List GetEmployeeDetails() - { - var data = EmployeeData.GetAllRecords().ToList(); - return data; - } - - /// - /// Returns all employee data for the POST request. - /// - /// Returns the full employee data as an IQueryable collection. - [HttpPost] - [Route("api/[controller]")] - public object Post([FromBody] DataManagerRequest DataManagerRequest) - { - // Retrieve data from the data source (e.g., database). - IQueryable DataSource = GetEmployeeDetails().AsQueryable(); - return DataSource; - } - } -} - -{% endhighlight %} -{% endtabs %} - -**8. Add Grid, AutoComplete and configure with server** - -To implement a Grid with an editable foreign key column using **AutoComplete** with remote data, add the following code to the **Home.razor** file: +> For detailed configuration of remote data operations, refer to the [UrlAdaptor documentation](https://blazor.syncfusion.com/documentation/datagrid/connecting-to-adaptors/url-adaptor). {% tabs %} {% highlight razor tabtitle="Home.razor" %} @@ -1343,35 +1014,41 @@ To implement a Grid with an editable foreign key column using **AutoComplete** w @using EditTemplate.Models @using Syncfusion.Blazor.DropDowns - - - //Use remote server host number instead ****. - + + + + + + + + - + - - + - + @{ var data = context as OrdersDetails; } - - //Use remote server host number instead ****. - - + + + + -@code { +@code { public class OrdersDetails { public int? OrderID { get; set; } @@ -1390,9 +1067,4 @@ To implement a Grid with an editable foreign key column using **AutoComplete** w {% endhighlight %} {% endtabs %} - -**5. Run the application** - -When you run the application, the Grid will display data fetched from the API. - ![Edit template in foreign key column using remote data](./images/edit-template.gif)