Skip to content

Commit 5d82321

Browse files
Merge pull request #1 from SyncfusionExamples/883534
MAUI - 883534 - How to populate data using WebAPI in MAUI DataGrid?
2 parents d9e8d8d + 11ef59c commit 5d82321

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+1290
-2
lines changed

README.md

Lines changed: 107 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,107 @@
1-
# How-to-populate-data-using-WebAPI-in-MAUI-DataGrid-
2-
How to populate data using WebAPI in MAUI DataGrid?
1+
# How to populate data using WebAPI in MAUI DataGrid?
2+
The [.NET MAUI DataGrid](https://www.syncfusion.com/maui-controls/maui-datagrid) supports binding the item source from a Web API.
3+
4+
##### C#
5+
Create a **JSON** data model.
6+
7+
**OrderInfo**
8+
```C#
9+
public class OrderInfo
10+
{
11+
public int OrderID { get; set; }
12+
public string? CustomerID { get; set; }
13+
public int EmployeeID { get; set; }
14+
public double Freight { get; set; }
15+
public string? ShipCity { get; set; }
16+
public bool Verified { get; set; }
17+
public DateTime OrderDate { get; set; }
18+
public string? ShipName { get; set; }
19+
public string? ShipCountry { get; set; }
20+
public DateTime ShippedDate { get; set; }
21+
public string? ShipAddress { get; set; }
22+
}
23+
```
24+
Create a WebApiServices class within the Services folder.
25+
26+
**WebApiServices**
27+
28+
Utilize the webApiUrl to retrive the data using the ReadDataAsync() function. Read the response using the **ReadAsStringAsync()** method and deserialize the JSON object using the [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json) package.
29+
30+
```C#
31+
internal class WebApiServices
32+
{
33+
#region Fields
34+
35+
public static string webApiUrl = "https://ej2services.syncfusion.com/production/web-services/api/Orders"; // Your Web Api here
36+
37+
HttpClient client;
38+
39+
#endregion
40+
41+
#region Constructor
42+
43+
public WebApiServices()
44+
{
45+
client = new HttpClient();
46+
}
47+
48+
#endregion
49+
50+
#region RefreshDataAsync
51+
52+
/// <summary>
53+
/// Retrieves data from the web service.
54+
/// </summary>
55+
/// <returns>Returns the ObservableCollection.</returns>
56+
public async Task<ObservableCollection<OrderInfo>>? ReadDataAsync()
57+
{
58+
var uri = new Uri(webApiUrl);
59+
try
60+
{
61+
//Sends request to retrieve data from the web service for the specified Uri
62+
var response = await client.GetAsync(uri);
63+
64+
if (response.IsSuccessStatusCode)
65+
{
66+
var content = await response.Content.ReadAsStringAsync(); //Returns the response as JSON string
67+
return JsonConvert.DeserializeObject<ObservableCollection<OrderInfo>>(content)!; //Converts JSON string to ObservableCollection
68+
}
69+
}
70+
catch (Exception ex)
71+
{
72+
System.Diagnostics.Debug.WriteLine(@"ERROR {0}", ex.Message);
73+
}
74+
75+
return null;
76+
}
77+
78+
#endregion
79+
}
80+
```
81+
82+
**OrderInfoViewModel**
83+
84+
Populate the data using the ReadDataAsync() in the viewmodel.
85+
86+
```C#
87+
private async void GenerateData()
88+
{
89+
OrderInfoCollection = await webApiServices.ReadDataAsync()!;
90+
}
91+
```
92+
93+
The following screenshot shows how to to populate data using WebAPI in MAUI DataGrid.
94+
95+
![DataGrid with JSON data](SfDataGrid_WebApi.png)
96+
97+
[View sample in GitHub](https://github.com/SyncfusionExamples/How-to-populate-data-using-WebAPI-in-MAUI-DataGrid)
98+
99+
Take a moment to pursue this [documentation](https://help.syncfusion.com/maui/datagrid/overview), where you can find more about Syncfusion .NET MAUI DataGrid (SfDataGrid) with code examples.
100+
Please refer to this [link](https://www.syncfusion.com/maui-controls/maui-datagrid) to learn about the essential features of Syncfusion .NET MAUI DataGrid(SfDataGrid).
101+
102+
### Conclusion
103+
I hope you enjoyed learning about how to populate data using WebAPI in MAUI DataGrid.
104+
105+
You can refer to our [.NET MAUI DataGrid's feature tour](https://www.syncfusion.com/maui-controls/maui-datagrid) page to know about its other groundbreaking feature representations. You can also explore our .NET MAUI DataGrid Documentation to understand how to present and manipulate data.
106+
For current customers, you can check out our .NET MAUI components from the [License and Downloads](https://www.syncfusion.com/account/downloads) page. If you are new to Syncfusion, you can try our 30-day free trial to check out our .NET MAUI DataGrid and other .NET MAUI components.
107+
If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our [support forums](https://www.syncfusion.com/forums), [Direct-Trac](https://support.syncfusion.com/account/login?ReturnUrl=%2Faccount%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dc54e52f3eb3cde0c3f20474f1bc179ed%26redirect_uri%3Dhttps%253A%252F%252Fsupport.syncfusion.com%252Fagent%252Flogincallback%26response_type%3Dcode%26scope%3Dopenid%2520profile%2520agent.api%2520integration.api%2520offline_access%2520kb.api%26state%3D8db41f98953a4d9ba40407b150ad4cf2%26code_challenge%3DvwHoT64z2h21eP_A9g7JWtr3vp3iPrvSjfh5hN5C7IE%26code_challenge_method%3DS256%26response_mode%3Dquery) or [feedback portal](https://www.syncfusion.com/feedback/maui?control=sfdatagrid). We are always happy to assist you!

SfDataGridSample/App.xaml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?xml version = "1.0" encoding = "UTF-8" ?>
2+
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
3+
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
4+
xmlns:local="clr-namespace:SfDataGridSample"
5+
x:Class="SfDataGridSample.App">
6+
<Application.Resources>
7+
<ResourceDictionary>
8+
<ResourceDictionary.MergedDictionaries>
9+
<ResourceDictionary Source="Resources/Styles/Colors.xaml" />
10+
<ResourceDictionary Source="Resources/Styles/Styles.xaml" />
11+
</ResourceDictionary.MergedDictionaries>
12+
</ResourceDictionary>
13+
</Application.Resources>
14+
</Application>

SfDataGridSample/App.xaml.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
namespace SfDataGridSample
2+
{
3+
public partial class App : Application
4+
{
5+
public App()
6+
{
7+
InitializeComponent();
8+
9+
MainPage = new AppShell();
10+
}
11+
}
12+
}

SfDataGridSample/AppShell.xaml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?xml version="1.0" encoding="UTF-8" ?>
2+
<Shell
3+
x:Class="SfDataGridSample.AppShell"
4+
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
5+
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
6+
xmlns:local="clr-namespace:SfDataGridSample"
7+
Shell.FlyoutBehavior="Disabled"
8+
Title="SfDataGridSample">
9+
10+
<ShellContent
11+
Title="Home"
12+
ContentTemplate="{DataTemplate local:MainPage}"
13+
Route="MainPage" />
14+
15+
</Shell>

SfDataGridSample/AppShell.xaml.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
namespace SfDataGridSample
2+
{
3+
public partial class AppShell : Shell
4+
{
5+
public AppShell()
6+
{
7+
InitializeComponent();
8+
}
9+
}
10+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
using Newtonsoft.Json;
2+
using SfDataGridSample.Model;
3+
using System.Collections.ObjectModel;
4+
5+
namespace SfDataGridSample
6+
{
7+
internal class WebApiServices
8+
{
9+
#region Fields
10+
11+
public static string webApiUrl = "https://ej2services.syncfusion.com/production/web-services/api/Orders"; // Your Web Api here
12+
13+
HttpClient client;
14+
15+
#endregion
16+
17+
#region Constructor
18+
public WebApiServices()
19+
{
20+
client = new HttpClient();
21+
}
22+
#endregion
23+
24+
#region RefreshDataAsync
25+
26+
/// <summary>
27+
/// Retrieves data from the web service.
28+
/// </summary>
29+
/// <returns>Returns the ObservableCollection.</returns>
30+
public async Task<ObservableCollection<OrderInfo>>? ReadDataAsync()
31+
{
32+
var uri = new Uri(webApiUrl);
33+
try
34+
{
35+
//Sends request to retrieve data from the web service for the specified Uri
36+
var response = await client.GetAsync(uri);
37+
38+
if (response.IsSuccessStatusCode)
39+
{
40+
var content = await response.Content.ReadAsStringAsync(); //Returns the response as JSON string
41+
return JsonConvert.DeserializeObject<ObservableCollection<OrderInfo>>(content)!; //Converts JSON string to ObservableCollection
42+
}
43+
}
44+
catch (Exception ex)
45+
{
46+
System.Diagnostics.Debug.WriteLine(@"ERROR {0}", ex.Message);
47+
}
48+
49+
return null;
50+
}
51+
#endregion
52+
}
53+
}

SfDataGridSample/MainPage.xaml

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?xml version="1.0" encoding="utf-8" ?>
2+
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
3+
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
4+
xmlns:syncfusion="clr-namespace:Syncfusion.Maui.DataGrid;assembly=Syncfusion.Maui.DataGrid"
5+
xmlns:local="clr-namespace:SfDataGridSample"
6+
x:Class="SfDataGridSample.MainPage">
7+
8+
<ContentPage.BindingContext>
9+
<local:OrderInfoViewModel/>
10+
</ContentPage.BindingContext>
11+
12+
<syncfusion:SfDataGrid ItemsSource="{Binding OrderInfoCollection}"
13+
ColumnWidthMode="Auto"
14+
GridLinesVisibility="Both"
15+
HeaderGridLinesVisibility="Both">
16+
<syncfusion:SfDataGrid.Columns>
17+
<syncfusion:DataGridNumericColumn MappingName="OrderID" HeaderText="Order ID" Format="d"/>
18+
<syncfusion:DataGridTextColumn MappingName="CustomerID" HeaderText="Customer ID"/>
19+
<syncfusion:DataGridTextColumn MappingName="ShipName" HeaderText="Ship Name"/>
20+
</syncfusion:SfDataGrid.Columns>
21+
</syncfusion:SfDataGrid>
22+
23+
24+
25+
</ContentPage>

SfDataGridSample/MainPage.xaml.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using Syncfusion.Maui.DataGrid;
2+
using System;
3+
using System.Data;
4+
using System.Data.Common;
5+
using System.Reflection;
6+
namespace SfDataGridSample
7+
{
8+
public partial class MainPage : ContentPage
9+
{
10+
public MainPage()
11+
{
12+
InitializeComponent();
13+
}
14+
15+
}
16+
17+
18+
}

SfDataGridSample/MauiProgram.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using Microsoft.Extensions.Logging;
2+
using Syncfusion.Maui.Core.Hosting;
3+
4+
namespace SfDataGridSample
5+
{
6+
public static class MauiProgram
7+
{
8+
public static MauiApp CreateMauiApp()
9+
{
10+
var builder = MauiApp.CreateBuilder();
11+
builder
12+
.UseMauiApp<App>()
13+
.ConfigureSyncfusionCore()
14+
.ConfigureFonts(fonts =>
15+
{
16+
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
17+
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
18+
});
19+
20+
#if DEBUG
21+
builder.Logging.AddDebug();
22+
#endif
23+
24+
return builder.Build();
25+
}
26+
}
27+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
namespace SfDataGridSample.Model
2+
{
3+
public class OrderInfo
4+
{
5+
public int OrderID { get; set; }
6+
public string? CustomerID { get; set; }
7+
public int EmployeeID { get; set; }
8+
public double Freight { get; set; }
9+
public string? ShipCity { get; set; }
10+
public bool Verified { get; set; }
11+
public DateTime OrderDate { get; set; }
12+
public string? ShipName { get; set; }
13+
public string? ShipCountry { get; set; }
14+
public DateTime ShippedDate { get; set; }
15+
public string? ShipAddress { get; set; }
16+
}
17+
}

0 commit comments

Comments
 (0)