diff --git a/blazor/common/data-binding/data-updates.md b/blazor/common/data-binding/data-updates.md
index b12c053a82..756a9374dd 100644
--- a/blazor/common/data-binding/data-updates.md
+++ b/blazor/common/data-binding/data-updates.md
@@ -1,7 +1,7 @@
---
layout: post
title: ObservableCollection and INotifyPropertyChanged in Syncfusion Blazor
-description: Learn how Syncfusion Blazor components react to changes from ObservableCollection and INotifyPropertyChanged without manual refresh. Explore to more details.
+description: Learn how Syncfusion Blazor components automatically update with ObservableCollection and INotifyPropertyChanged, eliminating manual refresh.
platform: Blazor
component: Common
documentation: ug
@@ -9,64 +9,76 @@ documentation: ug
# Data updates with Interface
-Syncfusion® Blazor components automatically update UI when bound data implements `INotifyCollectionChanged` (`ObservableCollection`) or `INotifyPropertyChanged`.
+Syncfusion® Blazor components provide automatic UI updates when the bound data source uses `ObservableCollection` and implements [INotifyCollectionChanged](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.inotifycollectionchanged?view=net-10.0) or [INotifyPropertyChanged](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged?view=net-10.0). These interfaces enable real-time synchronization between the data model and the component without requiring explicit refresh calls.
-## ObservableCollection
+**Key Difference:**
+
+- Use `ObservableCollection` with `INotifyCollectionChanged` for **collection-level changes** such as adding or removing items.
+- Use `INotifyPropertyChanged` for **property-level changes** within individual items, such as updating an existing record.
-Data-bound components (such as DataGrid, Kanban, Scheduler) provides support to update its data without any additional refresh call when using `ObservableCollection` as data source and perform add, remove, clear actions in collection. ObservableCollection notifies the collection changes using [INotifyCollectionChanged](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.inotifycollectionchanged) interface.
+## ObservableCollection
-In the following example, the DataGrid updates automatically when items are added to or removed from the `ObservableCollection`.
+Data-bound components such as `DataGrid`, `Kanban`, and `Scheduler` support automatic UI updates when an `ObservableCollection` is used as the data source. These components handle operations like **Add**, **Remove**, and **Clear** performed on the collection without requiring additional refresh calls. `ObservableCollection` achieves this by implementing the [INotifyCollectionChanged](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.inotifycollectionchanged) interface, which raises notifications whenever the collection is modified.
```cshtml
-@using System.Collections.ObjectModel;
+@using System.Collections.ObjectModel
@using Syncfusion.Blazor.Grids
@using Syncfusion.Blazor.Buttons
-Add Record
-Delete Record
-
-
-
+Add Record
+Delete Record
+
+
-
-
-
-
+
+
+
+
-@code{
- private ObservableCollection observableData { get; set; }
+@code {
+
+ private ObservableCollection observableData = new ObservableCollection();
+
private int uniqueId;
protected override void OnInitialized()
{
- observableData = new ObservableCollection(Enumerable.Range(1, 5).Select(x => new DataOrder()
- {
- OrderID = 10000 + x,
- CustomerName = (new string[] { "ALFKI", "ANANTR", "ANTON", "BLONP", "BOLID" })[new Random().Next(5)],
- Freight = 2.1 * x,
- OrderDate = DateTime.Now.AddDays(-x),
- }));
+ observableData = new ObservableCollection(
+ Enumerable.Range(1, 5).Select(x => new DataOrder
+ {
+ OrderID = 10000 + x,
+ CustomerName = new[] { "ALFKI", "ANANTR", "ANTON", "BLONP", "BOLID" }[new Random().Next(5)],
+ Freight = 2.1 * x,
+ OrderDate = DateTime.Now.AddDays(-x)
+ })
+ );
}
private void AddRecord()
{
- observableData.Add(new DataOrder() { OrderID = 10010 + ++uniqueId, CustomerName = "VINET", Freight = 30.35, OrderDate = new DateTime(1991, 05, 15) });
+ observableData.Add(new DataOrder
+ {
+ OrderID = 10010 + ++uniqueId,
+ CustomerName = "VINET",
+ Freight = 30.35,
+ OrderDate = new DateTime(1991, 05, 15)
+ });
}
private void DeleteRecord()
{
- if (observableData.Count() != 0)
+ if (observableData.Count > 0)
{
observableData.Remove(observableData.First());
}
}
- public class DataOrder
+ private class DataOrder
{
public int OrderID { get; set; }
- public string CustomerName { get; set; }
+ public string? CustomerName { get; set; }
public DateTime OrderDate { get; set; }
public double Freight { get; set; }
}
@@ -104,75 +116,79 @@ In the following example, the DataGrid updates automatically when items are adde
## INotifyPropertyChanged
-Data-bound components (such as DataGrid, Kanban, and Scheduler) provides support to update its data without any additional refresh call when changing property value of item if an item implements [INotifyPropertyChanged ](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged) interface. `INotifyPropertyChanged` interface is used to notify, that a property value has changed.
-
-In the following example, the `DataOrder` type implements `INotifyPropertyChanged` and raises the [PropertyChanged](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged.propertychanged) event when a property value changes. DataGrid automatically updates its property values are changed in data object by listening to `PropertyChanged` event.
+Data-bound components such as `DataGrid`, `Kanban`, and `Scheduler` automatically refresh the UI when the underlying data type implements [INotifyPropertyChanged](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged). The interface raises the [PropertyChanged](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged.propertychanged?view=net-10.0) event whenever a property value changes, allowing the component to re-render without an explicit refresh call.
```cshtml
@using System.Collections.ObjectModel;
@using System.ComponentModel;
-@using Syncfusion.Blazor.Grids
-@using Syncfusion.Blazor.Buttons
+@using Syncfusion.Blazor.Grids;
+@using Syncfusion.Blazor.Buttons;
+
+Update Data
-Update Data
-
-
-
+
-
-
-
-
+
+
+
+
-@code{
- private ObservableCollection observableData { get; set; }
+@code {
+
+ private ObservableCollection observableData = new ObservableCollection();
private int uniqueId;
protected override void OnInitialized()
{
- observableData = new ObservableCollection(Enumerable.Range(1, 5).Select(x => new DataOrder()
- {
- OrderID = 10000 + x,
- CustomerName = (new string[] { "ALFKI", "ANANTR", "ANTON", "BLONP", "BOLID" })[new Random().Next(5)],
- Freight = 2.1 * x,
- OrderDate = DateTime.Now.AddDays(-x),
- }));
+ observableData = new ObservableCollection(
+ Enumerable.Range(1, 5).Select(x => new DataOrder
+ {
+ OrderID = 10000 + x,
+ CustomerName = new[] { "ALFKI", "ANANTR", "ANTON", "BLONP", "BOLID" }[new Random().Next(5)],
+ Freight = 2.1 * x,
+ OrderDate = DateTime.Now.AddDays(-x)
+ })
+ );
}
private void UpdateRecord()
{
- if (observableData.Count() != 0)
+ if (observableData.Count > 0)
{
- var name = observableData.First();
- name.CustomerName = "Record Updated";
+ var firstRecord = observableData.First();
+ firstRecord.CustomerName = "Record Updated";
}
}
- public class DataOrder : INotifyPropertyChanged
+ private class DataOrder : INotifyPropertyChanged
{
public int OrderID { get; set; }
- private string customerID { get; set; }
- public string CustomerName
+ private string? customerName;
+
+ public string? CustomerName
{
- get { return customerID; }
+ get => customerName;
set
{
- this.customerID = value;
- NotifyPropertyChanged("CustomerID");
+ if (customerName != value)
+ {
+ customerName = value;
+ NotifyPropertyChanged(nameof(CustomerName));
+ }
}
}
+
public DateTime OrderDate { get; set; }
public double Freight { get; set; }
- public event PropertyChangedEventHandler PropertyChanged;
+
+ public event PropertyChangedEventHandler? PropertyChanged;
+
private void NotifyPropertyChanged(string propertyName)
{
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
- }
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
-```
+```
\ No newline at end of file
diff --git a/blazor/common/data-binding/webapi-service-binding.md b/blazor/common/data-binding/webapi-service-binding.md
index 7dc70bc1d9..d190d9f421 100644
--- a/blazor/common/data-binding/webapi-service-binding.md
+++ b/blazor/common/data-binding/webapi-service-binding.md
@@ -9,227 +9,304 @@ documentation: ug
# Bind data to Blazor components using WebApiAdaptor and perform CRUD
-This article shows how to retrieve data from a WebAPI controller, bind it to the DataGrid using the [WebApiAdaptor](https://blazor.syncfusion.com/documentation/data/adaptors#web-api-adaptor) of `SfDataManager`, and perform CRUD operations.
+The Syncfusion® Blazor DataGrid supports data binding through the [SfDataManager](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Data.SfDataManager.html) component configured with [WebApiAdaptor](https://blazor.syncfusion.com/documentation/data/adaptors#web-api-adaptor). This adaptor is designed for scenarios where data is retrieved from **HTTP based Web API endpoints** that support **OData** query options. Since `WebApiAdaptor` extends [ODataAdaptor](https://blazor.syncfusion.com/documentation/data/adaptors#odata-adaptor), the API must process OData formatted queries included in requests.
-You can use the WebApiAdaptor of SfDataManager to interact with Web APIs created with OData endpoint. The WebApiAdaptor is extended from the ODataAdaptor. Hence, to use WebApiAdaptor, the endpoint should understand the OData formatted queries sent along with the request.
+**Key Capabilities of WebApiAdaptor**
-To enable the OData query option for Web API, Refer to this [documentation](https://learn.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options).
+* Enables communication with RESTful APIs instead of direct database access.
+* Supports OData query options for **filtering**, **sorting**, and **paging**.
+* Recommended for **Blazor WebAssembly** and **Auto** render mode to maintain security and scalability.
+
+**Why Use HTTP API with Auto Render Mode**
+
+The **Auto render mode** combines **Server** and **WebAssembly** interactivity, enabling hybrid rendering for improved performance and flexibility. In this configuration:
+
+* Database access must remain on the server to ensure security.
+* All data operations should be performed through **HTTP API endpoints**, preventing exposure of sensitive logic to client-side components.
+
+This approach maintains scalability and protects application integrity when using hybrid rendering.
+
+For other interactive render modes and interactivity locations, refer to Render Modes [documentation](https://blazor.syncfusion.com/documentation/common/interactive-render-mode).
## Prerequisite software
-The following software are required:
-* Visual Studio 2022
-* .NET 7.0 or .NET 8.0 or .NET 9.0 or .NET 10
+Before configuring the Syncfusion® Blazor DataGrid with Web API services, ensure the following:
-## Create the database
+- [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/)
+- .[NET SDK](https://dotnet.microsoft.com/en-us/download/dotnet) (**version 8.0 or later**; supports **.NET 8**, **.NET 9**, and **.NET 10** for Blazor Web Apps and Blazor Server projects)
-Open Visual Studio , select **View -> SQL Server Object Explorer**. Right-click on the Databases folder to create a new Database and name it as OrdersDetails.
+## Create SQL Server database
-
-
+A **SQL Server** database is required to store order details for the Blazor application. The database will be used by the API controller to perform **CRUD** operations.
-Right-click on the **Tables** folder of the created database and click **Add New Table**.
+1. **Open SQL Server Object Explorer in Visual Studio**
-
+ Navigate to: **View → SQL Server Object Explorer**.
-Use the following query to add a new table named **Orders**.
+2. **Create a New Database**
-```
-Create Table Orders(
- OrderID BigInt Identity(1,1) Primary Key Not Null,
- CustomerID Varchar(100) Not Null,
- Freight int Null,
- OrderDate datetime null
-)
-```
+ * Right-click the **Databases** folder.
+ * Select **Add New Database**.
-Now, the Orders table design will look like below. Click on the **Update** button.
+ 
-
+ * Name the database **OrdersDetails**.
-Now, click on **Update Database**.
+ 
-
+3. **Add a New Table**
-## Create a new Blazor Web App
+ * Right-click the **Tables** folder in the created database.
+ * Select **Add New Table**.
-Create a **Blazor Web App** using Visual Studio 2022 via [Microsoft templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio).
+ 
-Configure the appropriate [interactive render mode](https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes#render-modes) and [interactivity location](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling#interactivity-location) when creating the Blazor Web App.
+4. **Create Orders Table Using SQL Script**
-### Generate DbContext and model class from the database
+ Use this script to create the table:
-Now, you need to scaffold **DbContext** and **model classes** from the existing **OrdersDetails** database. To perform scaffolding and work with the SQL Server database in our application, install the following NuGet packages.If you have created a Blazor Web App with the `Interactive render mode` set to `WebAssembly` or `Auto` ensure to follow these steps:
+ ```
+ CREATE TABLE Orders (
+ OrderID BIGINT IDENTITY(1,1) PRIMARY KEY NOT NULL,
+ CustomerID VARCHAR(100) NOT NULL,
+ Freight INT NULL,
+ OrderDate DATETIME NULL
+ );
+ ```
-* Create the new project with Class Library template named as `BlazorWebApp.Shared` for DbContext and model class as shown below.
-
+5. **Apply Changes**
-Additionally, ensure that you have added a reference to the `BlazorWebApp.Shared` project in both the server-side and client-side projects of your web application.
+ * Review the table design.
+ * Select **Update** to apply changes.
-* Then, open the NuGet Package Manager and install the following packages in both the shared and server-side projects of your Blazor Web App.
+ 
- * [Microsoft.EntityFrameworkCore.Tools](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools): This package creates database context and model classes from the database.
- * [Microsoft.EntityFrameworkCore.SqlServer](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/): The database provider that allows Entity Framework Core to work with SQL Server.
+ * Select **Update Database** to finalize the schema.
-Alternatively, you can utilize the following package manager command to achieve the same.
+ 
-{% tabs %}
-{% highlight C# tabtitle="Package Manager" %}
+N> **Download SQL Script**: 
-Install-Package Microsoft.EntityFrameworkCore.Tools
+## Set Up Blazor Web App
-Install-Package Microsoft.EntityFrameworkCore.SqlServer
+Create a Blazor Web App using Visual Studio 2022 with [Microsoft Blazor templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-10.0&pivots=vs) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio) for streamlined project creation.
-{% endhighlight %}
-{% endtabs %}
+1. Open **Visual Studio 2022**.
+2. Select **Create a new project**.
+3. Choose the **Blazor Web App** template.
+4. Configure project options such as **name**, **location**, and **.NET version**.
+5. Set [interactive render mode](https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-10.0#render-modes) to **Auto** for hybrid interactivity.
+6. Define [interactivity location](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-10.0&pivots=vs#interactivity-location) as **Per page/component** or **Global** based on requirements.
-Once the above packages are installed, you can scaffold DbContext and Model classes. Run the following command in the Package Manager Console under the `BlazorWebApp.Shared` project.
+## Generate DbContext and model classes
-```
-Scaffold-DbContext “Server=localhost;Database=OrdersDetails;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data
-```
+**Entity Framework Core** is used to scaffold the **DbContext** and model classes from the **OrdersDetails** database. This configuration enables strongly typed interaction with **SQL Server**.
-The above scaffolding command contains the following details for creating DbContext and model classes for the existing database and its tables.
- * **Connection string**: Server=localhost;Database=OrdersDetails;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
- * **Data provider**: Microsoft.EntityFrameworkCore.SqlServer
- * **Output directory**: -OutputDir Data
+When using **Auto render mode** or **Blazor WebAssembly**:
-After running the above command, **OrdersDetailsContext.cs** and **Orders.cs** files will be created under the Data folder of `BlazorWebApp.Shared` project as follows.
+* Do not access the database directly from client-side components.
+* Keep DbContext and model classes in the **server-side project**.
+* Use **HTTP API endpoints** for all data operations to maintain security and scalability.
-
+**Steps**
-You can see that OrdersDetailsContext.cs file contains the connection string details in the **OnConfiguring** method.
+1. **Install Required NuGet Packages**
-{% tabs %}
-{% highlight c# tabtitle="OrdersDetailsContext.cs" hl_lines="21 22 23" %}
+ In the **server-side project**, install:
-using Microsoft.EntityFrameworkCore;
+ - [Microsoft.EntityFrameworkCore.Tools](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools) – Provides scaffolding commands.
+ - [Microsoft.EntityFrameworkCore.SqlServer](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/) – Enables SQL Server support.
-namespace BlazorWebApp.Shared.Data;
+ **Options to install:**
-public partial class OrdersDetailsContext : DbContext
-{
- public OrdersDetailsContext()
- {
- }
+ * Using **NuGet Package Manager** in Visual Studio:
+
+ Navigate to: *Tools → NuGet Package Manager → Manage NuGet Packages for Solution*.
- public OrdersDetailsContext(DbContextOptions options)
- : base(options)
+ * Using **Package Manager Console**:
+
+ {% tabs %}
+ {% highlight C# tabtitle="Package Manager" %}
+
+ Install-Package Microsoft.EntityFrameworkCore.Tools
+
+ Install-Package Microsoft.EntityFrameworkCore.SqlServer
+
+ {% endhighlight %}
+ {% endtabs %}
+
+2. **Run Scaffolding Command**
+
+ Execute this command in the **Package Manager Console**:
+
+ ```powershell
+ Scaffold-DbContext "Server=localhost;Database=OrdersDetails;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data
+ ```
+
+ This creates:
+
+ * **OrdersDetailsContext.cs** – Database context.
+ * **Orders.cs** – Entity class for the Orders table.
+
+ {% tabs %}
+ {% highlight c# tabtitle="OrdersDetailsContext.cs" hl_lines="21 22 23" %}
+
+ using Microsoft.EntityFrameworkCore;
+
+ namespace BlazorWebApp.Shared.Data;
+
+ public partial class OrdersDetailsContext : DbContext
{
+ public OrdersDetailsContext()
+ {
+ }
+
+ public OrdersDetailsContext(DbContextOptions options)
+ : base(options)
+ {
+ }
+
+ public virtual DbSet Orders { get; set; }
+
+ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)=> optionsBuilder.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=OrdersDetails;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
+ .....
}
+ {% endhighlight %}
+ {% endtabs %}
- public virtual DbSet Orders { get; set; }
+3. **Store Connection String in appsettings.json**
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)=> optionsBuilder.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=OrdersDetails;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
- .....
-}
-{% endhighlight %}
-{% endtabs %}
+ Avoid hardcoding connection strings in **OnConfiguring**. Use **appsettings.json**:
-Additionally ensure the connection strings added in the **appsettings.json** file of server side project of your Web App.
+ ```json
+ {
+ "ConnectionStrings": {
+ "OrdersDetailsDatabase": "Server=(localdb)\\MSSQLLocalDB;Database=OrdersDetails;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
+ }
+ }
+ ```
-```
-{
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft.AspNetCore": "Warning"
- }
- },
- "AllowedHosts": "*",
- "ConnectionStrings": {
- "OrdersDetailsDatabase": "Server=(localdb)\\MSSQLLocalDB;Database=OrdersDetails;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
- }
-}
-```
-* Now, the DbContext must be configured using connection string and registered as scoped service using the AddDbContext method in **Program.cs** of server side project only.
+4. **Register DbContext in Program.cs**
-```
-builder.Services.AddDbContext(option =>
- option.UseSqlServer(builder.Configuration.GetConnectionString("OrdersDetailsDatabase")));
-```
+ Configure the context using dependency injection:
-### Creating API Controller
+ ```cshtml
+ builder.Services.AddDbContext(options =>
+ options.UseSqlServer(builder.Configuration.GetConnectionString("OrdersDetailsDatabase")));
+ ```
-The application is now configured to connect with the **OrdersDetails** database using Entity Framework. Now, it’s time to consume data from the OrdersDetails database. To do so, you need a Web API controller to serve data from the DbContext to the Blazor application.
+N> **Security Best Practice**: Hardcoding sensitive information in source files is a security risk. Always use configuration files or secure secrets management.
-To create a Web API controller, right-click the **Controller** folder in the Server side project and select **Add -> New Item -> API controller with read/write actions** to create a new Web API controller. We are naming this controller as OrdersController as it returns Orders table records.
+### Create API Controller for CRUD operations
-Now, replace the Web API controller with the following code which contains code to handle CRUD operations in the Orders table.
+The API controller exposes endpoints for performing **Create**, **Read**, **Update**, and **Delete** (**CRUD**) operations on the **OrdersDetails** database. This ensures that Blazor components interact with the database through HTTP APIs rather than direct DbContext access, which is essential for **Auto** render mode and **Blazor WebAssembly**.
-{% tabs %}
-{% highlight c# tabtitle="OrdersController.cs" %}
+**Steps**
-using Microsoft.AspNetCore.Mvc;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using WebAPICRUDServerApp.Data;
+1. **Add a New API Controller**
+
+ 1. In the server-side project, right-click the **Controllers** folder.
+ 2. Select **Add → New Item → API Controller with read/write actions**.
+ 3. Name the controller **OrdersController**.
+
+2. **Implement CRUD Operations**
+
+ Replace the default code with this implementation:
+
+ {% tabs %}
+ {% highlight c# tabtitle="OrdersController.cs" %}
+
+ using Microsoft.AspNetCore.Mvc;
+ using System.Linq;
+ using WebAPICRUDServerApp.Data;
-namespace WebAPICRUDServerApp
-{
[Route("api/[controller]")]
[ApiController]
public class OrdersController : ControllerBase
{
- private OrdersDetailsContext _context;
+ private readonly OrdersDetailsContext _context;
+
public OrdersController(OrdersDetailsContext context)
{
_context = context;
}
- // GET: api/
+
+ // GET: api/Orders
[HttpGet]
- public object Get()
+ public IActionResult Get()
{
- return new { Items = _context.Orders, Count = _context.Orders.Count() };
+ var items = _context.Orders.ToList();
+ return Ok(new { Items = items, Count = items.Count });
}
- // POST api/
+
+ // POST: api/Orders
[HttpPost]
- public void Post([FromBody] Orders book)
+ public IActionResult Post([FromBody] Orders order)
{
- _context.Orders.Add(book);
+ _context.Orders.Add(order);
_context.SaveChanges();
+ return Ok(order);
}
- // PUT api/
- [HttpPut]
- public void Put(long id, [FromBody] Orders book)
+
+ // PUT: api/Orders/{id}
+ [HttpPut("{id}")]
+ public IActionResult Put(long id, [FromBody] Orders order)
{
- Orders _book = _context.Orders.Where(x => x.OrderId.Equals(book.OrderId)).FirstOrDefault();
- _book.CustomerId = book.CustomerId;
- _book.Freight = book.Freight;
- _book.OrderDate = book.OrderDate;
+ var existingOrder = _context.Orders.FirstOrDefault(x => x.OrderId == id);
+ if (existingOrder == null) return NotFound();
+
+ existingOrder.CustomerId = order.CustomerId;
+ existingOrder.Freight = order.Freight;
+ existingOrder.OrderDate = order.OrderDate;
+
_context.SaveChanges();
+ return Ok(existingOrder);
}
- // DELETE api/
+
+ // DELETE: api/Orders/{id}
[HttpDelete("{id}")]
- public void Delete(long id)
+ public IActionResult Delete(long id)
{
- Orders _book = _context.Orders.Where(x => x.OrderId.Equals(id)).FirstOrDefault();
- _context.Orders.Remove(_book);
+ var order = _context.Orders.FirstOrDefault(x => x.OrderId == id);
+ if (order == null) return NotFound();
+
+ _context.Orders.Remove(order);
_context.SaveChanges();
+ return Ok();
}
}
-}
-{% endhighlight %}
-{% endtabs %}
+ {% endhighlight %}
+ {% endtabs %}
-* Now, open **Program.cs** file and add **AddControllers & MapControllers** method as follows.
+3. **Ensure Response Format for DataGrid Integration**
-{% tabs %}
-{% highlight c# tabtitle=".NET 10, .NET 9 & .NET 8 (~/Program.cs)" %}
+ The GET method must return a **JSON** object with:
-......
-builder.Services.AddControllers();
-....
-app.MapControllers();
-.....
+ * **Items**: A collection of entities.
+ * **Count**: Total number of entities.
-{% endhighlight %}
-{% endtabs %}
+ ```
+ {
+ "Items": [{...}, {...}, {...}],
+ "Count": 830
+ }
+ ```
+
+4. **Register Controller Routes**
+
+ In **Program.cs**, enable controller routing:
+
+ {% tabs %}
+ {% highlight c# tabtitle=".NET 8 or later (~/Program.cs)" %}
+
+ builder.Services.AddControllers();
+ app.MapControllers();
+
+ {% endhighlight %}
+ {% endtabs %}
-## Create Blazor Server Application
+
-## Add Syncfusion® Blazor DataGrid package
+## Install Syncfusion Blazor Packages
-To add **Blazor DataGrid** component 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/) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/).
+**Steps to Install and Configure**
-If using `WebAssembly` or `Auto` render modes in a Blazor Web App, install Syncfusion® Blazor NuGet packages in the client project.
+1. **Install Required NuGet Packages**
-Alternatively, you can utilize the following package manager command to achieve the same.
+ * For **Blazor Server** projects, install the following packages in the **server** project:
-{% tabs %}
-{% highlight C# tabtitle="Package Manager" %}
+ * [Syncfusion.Blazor.Grid](https://www.nuget.org/packages/Syncfusion.Blazor.Grid/)
+ * [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/)
-Install-Package Syncfusion.Blazor.Grid -Version {{ site.releaseversion }}
-Install-Package Syncfusion.Blazor.Themes -Version {{ site.releaseversion }}
+ * For **Blazor Web Apps** using **Auto** or **WebAssembly** render modes, install these packages in the **client** project.
-{% endhighlight %}
-{% endtabs %}
+ **Options to install:**
-N> Syncfusion® Blazor components are available in [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for available NuGet packages list with component details.
+ * Using NuGet Package Manager in Visual Studio:
-Open **~/_Imports.razor** file and import the following namespace.
+ Navigate to: *Tools → NuGet Package Manager → Manage NuGet Packages for Solution*
+
+ * Using Package Manager Console:
-{% highlight razor %}
+ ```powershell
+ Install-Package Syncfusion.Blazor.Grid -Version {{ site.releaseversion }}
+ Install-Package Syncfusion.Blazor.Themes -Version {{ site.releaseversion }}
+ ```
+> Syncfusion® Blazor components are available on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) for a complete list.
-@using Syncfusion.Blazor
-@using Syncfusion.Blazor.Grids
+2. **Import Required Namespaces**
-{% endhighlight %}
+ Add the following namespaces in the **~/_Imports.razor** file:
-Now, register the Syncfusion® Blazor Service in the **~/Program.cs** file of your App.
+ {% highlight razor %}
-For a Blazor Web App with `WebAssembly` or `Auto (Server and WebAssembly)` interactive render mode, register the Syncfusion® Blazor service in both **~/Program.cs** files of your web app.
+ @using Syncfusion.Blazor
+ @using Syncfusion.Blazor.Grids
-```cshtml
+ {% endhighlight %}
-....
-using Syncfusion.Blazor;
-....
-builder.Services.AddSyncfusionBlazor();
-....
+3. **Register Syncfusion Services**
-```
+ Register Syncfusion Blazor services in the **Program.cs** file:
-Themes provide life to components. Syncfusion® Blazor has different themes. They are:
+ ```cshtml
+ using Syncfusion.Blazor;
-* Fabric
-* Bootstrap
-* Material
-* High Contrast
+ builder.Services.AddSyncfusionBlazor();
+ ```
-In this demo application, the latest theme is used.
+ * For **Auto** render mode, register Syncfusion services in both **Program.cs** files (client and server projects).
+ * For **Blazor Server**, register in the server-side **Program.cs** only.
-* For **Blazor Web App**, refer stylesheet inside the `` of **~/Components/App.razor** file for .NET 10, .NET 9 and .NET 8.
-* For **Blazor WebAssembly application**, refer stylesheet inside the `` element of **wwwroot/index.html** file.
-* For **Blazor Server application**, refer stylesheet inside the `` element of
- * **~/Pages/_Host.cshtml** file for .NET 7.
- * **~/Pages/_Layout.cshtml** file for .NET 6.
+4. **Add Theme Stylesheet**
-{% highlight cshtml %}
+ Include the Syncfusion theme in the section:
-
+ {% highlight cshtml %}
-{% endhighlight %}
+
-Also, Include the script reference at the end of the `` of **~/Components/App.razor**(For Blazor Web App) or **Pages/_Host.cshtml** (for Blazor Server App) file as shown below:
+ {% endhighlight %}
-```html
-
- ....
-
-
-```
+ Add this stylesheet in the following locations based on the project type:
+
+ * **Blazor Web App**: **~/Components/App.razor**
+ * **Blazor WebAssembly**: **wwwroot/index.html**
+ * **Blazor Server**: **~/Pages/_Host.cshtml**
+
+5. **Add Script Reference**
+
+ Include the Syncfusion script at the end of the :
-## Add Syncfusion® Blazor DataGrid component to an application
+ ```html
+
-In previous steps, you have successfully configured the Syncfusion® Blazor package in the application. Now, you can add the grid component to the to the `.razor` page inside the `Pages` folder.
+
+
+ ```
-If you have set the interactivity location to `Per page/component` in the web app, ensure that you define a render mode at the top of the Syncfusion® Blazor component-included razor page as follows:
+## Add Syncfusion Blazor DataGrid
+
+The Syncfusion® Blazor DataGrid can be added to a Razor page and configured to bind data using SfDataManager with WebApiAdaptor.
+
+**Define Render Mode**
+
+If the interactivity location is set to **Per page/component**, specify the render mode at the top of the Razor page:
{% tabs %}
{% highlight razor %}
-@* Your App render mode define here *@
@rendermode InteractiveAuto
{% endhighlight %}
{% endtabs %}
+If the interactivity location is set to **Global**, the render mode is configured during project creation and does not need to be defined in individual Razor pages.
+
+**Add the DataGrid Component**
+
+Insert the Syncfusion [DataGrid](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.SfGrid-1.html) in a Razor page inside the **Pages** folder:
+
{% tabs %}
{% highlight razor %}
@@ -516,21 +607,23 @@ If you have set the interactivity location to `Per page/component` in the web ap
{% endhighlight %}
{% endtabs %}
-## Bind data to the Blazor DataGrid using WebApiAdaptor
+**Bind data Using SfDataManager and WebApiAdaptor**
-To consume data from the WebApi Controller, you need to add the **SfDataManager** with **WebApiAdaptor**. Refer to the following documentation for more details on [WebApiAdaptor](https://blazor.syncfusion.com/documentation/data/adaptors#web-api-adaptor).
+Use [SfDataManager](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Data.SfDataManager.html) with `WebApiAdaptor` to connect the grid to the API controller:
-{% tabs %}
-{% highlight razor %}
+ {% tabs %}
+ {% highlight razor %}
-
-
-
+
+
+
-{% endhighlight %}
-{% endtabs %}
+ {% endhighlight %}
+ {% endtabs %}
-Grid columns can be defined by using the [GridColumn](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html) component. We are going to create columns using the following code.
+**Define Grid Columns**
+
+Configure columns using the [GridColumn](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html) component:
{% tabs %}
{% highlight razor %}
@@ -548,57 +641,20 @@ Grid columns can be defined by using the [GridColumn](https://help.syncfusion.co
{% endhighlight %}
{% endtabs %}
-When you run the application, the `Get()` method will be called in your API controller.
+N> * References:
-{% tabs %}
-{% highlight c# %}
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using WebAPICRUDServerApp.Data;
-
-namespace WebAPICRUDServerApp
-{
- [Route("api/[controller]")]
- [ApiController]
- public class OrdersController : ControllerBase
- {
- private OrdersDetailsContext _context;
- public OrdersController(OrdersDetailsContext context)
- {
- _context = context;
- }
- // GET: api/
- [HttpGet]
- public object Get()
- {
- return new { Items = _context.Orders, Count = _context.Orders.Count() };
- }
- ...
- }
-}
-
-{% endhighlight %}
-{% endtabs %}
-
-The response object from the Web API should contain the properties, `Items` and `Count`, whose values are a collection of entities and the total count of the entities, respectively.
-
-The sample response object should look like this:
-
-```
-{
- "Items": [{..}, {..}, {..}, ...],
- "Count": 830
-}
-```
+> * [Syncfusion Blazor DataGrid Documentation](https://blazor.syncfusion.com/documentation/datagrid/getting-started)
+> * [Syncfusion Blazor DataManager Documentation](https://blazor.syncfusion.com/documentation/data/getting-started)
## Handling CRUD operations with our Syncfusion® Blazor DataGrid component
-You can enable editing in the grid component using the [GridEditSettings](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridEditSettings.html) component. Grid provides various modes of editing options such as [Inline/Normal](https://blazor.syncfusion.com/documentation/datagrid/in-line-editing), [Dialog](https://blazor.syncfusion.com/documentation/datagrid/dialog-editing), and [Batch](https://blazor.syncfusion.com/documentation/datagrid/batch-editing) editing.
+The Syncfusion® Blazor DataGrid supports editing through the [GridEditSettings](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridEditSettings.html) component. Editing modes include:
-Here, we are using **Inline** edit mode and used Toolbar property to show toolbar items for editing.
-We have added the DataGrid Editing and Toolbar code with previous Grid model.
+* [Inline](https://blazor.syncfusion.com/documentation/datagrid/in-line-editing)
+* [Dialog](https://blazor.syncfusion.com/documentation/datagrid/dialog-editing)
+* [Batch](https://blazor.syncfusion.com/documentation/datagrid/batch-editing).
+
+The [Toolbar](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.SfGrid-1.html#Syncfusion_Blazor_Grids_SfGrid_1_Toolbar) property displays action buttons such as **Add**, **Edit**, **Delete**, **Update**, and **Cancel** for performing **CRUD** operations.
{% tabs %}
{% highlight razor %}
@@ -617,23 +673,23 @@ We have added the DataGrid Editing and Toolbar code with previous Grid model.
{% endhighlight %}
{% endtabs %}
-N> Normal editing is the default mode. Set the [IsPrimaryKey](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_IsPrimaryKey) property to **true** for the column that holds a unique key.
+N> **Normal editing** is the default mode. Set the [IsPrimaryKey](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html#Syncfusion_Blazor_Grids_GridColumn_IsPrimaryKe) property to **true** for the column that holds a unique key.
### Insert a row
-To insert a new row, click the **Add** toolbar button. The new record edit form will look like below.
+Click **Add** in the toolbar to open a new row for data entry. After entering values, click **Update** to save the record. This triggers the **POST** method in the API controller:

-Clicking the **Update** toolbar button will insert the record in the Orders table by calling the following **POST** method of the Web API.
-
{% tabs %}
{% highlight c# tabtitle="OrdersController.cs" %}
-public void Post([FromBody] Orders book)
+[HttpPost]
+public IActionResult Post([FromBody] Orders order)
{
- _context.Orders.Add(book);
+ _context.Orders.Add(order);
_context.SaveChanges();
+ return Ok(order);
}
{% endhighlight %}
@@ -643,22 +699,23 @@ public void Post([FromBody] Orders book)
### Update a row
-To edit a row, select any row and click the **Edit** toolbar button. The edit form will look like below. Edit the Customer Name column.
+Select a row and click **Edit** to modify its values. After editing, click **Update** to apply changes. This invokes the **PUT** method:

-Clicking the **Update** toolbar button will update the record in the Orders table by calling the following **PUT** method of the Web API.
-
{% tabs %}
{% highlight c# tabtitle="OrdersController.cs" %}
-public void Put(long id, [FromBody] Orders book)
+[HttpPut("{id}")]
+public IActionResult Put(long id, [FromBody] Orders order)
{
- Orders _book = _context.Orders.Where(x => x.OrderId.Equals(book.OrderId)).FirstOrDefault();
- _book.CustomerId = book.CustomerId;
- _book.Freight = book.Freight;
- _book.OrderDate = book.OrderDate;
+ var existingOrder = _context.Orders.FirstOrDefault(x => x.OrderId == id);
+ if (existingOrder == null) return NotFound();
+ existingOrder.CustomerId = order.CustomerId;
+ existingOrder.Freight = order.Freight;
+ existingOrder.OrderDate = order.OrderDate;
_context.SaveChanges();
+ return Ok(existingOrder);
}
{% endhighlight %}
@@ -668,19 +725,22 @@ public void Put(long id, [FromBody] Orders book)
### Delete a row
-To delete a row, select any row and click the **Delete** toolbar button. Deleting operation will send a **DELETE** request to the Web API with the selected record`s primary key value to remove the corresponding record from the Orders table.
+Select a row and click **Delete** in the toolbar. This sends a **DELETE** request to remove the record:
{% tabs %}
{% highlight c# tabtitle="OrdersController.cs" %}
-public void Delete(long id)
+[HttpDelete("{id}")]
+public IActionResult Delete(long id)
{
- Orders _book = _context.Orders.Where(x => x.OrderId.Equals(id)).FirstOrDefault();
- _context.Orders.Remove(_book);
+ var order = _context.Orders.FirstOrDefault(x => x.OrderId == id);
+ if (order == null) return NotFound();
+ _context.Orders.Remove(order);
_context.SaveChanges();
+ return Ok();
}
{% endhighlight %}
{% endtabs %}
-N> Find the sample at this [GitHub repository](https://github.com/SyncfusionExamples/binding-webapi-services-and-perform-crud).
+N> Find the complete sample in the [GitHub repository](https://github.com/SyncfusionExamples/binding-webapi-services-and-perform-crud).