Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 107 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,107 @@
# How-to-populate-data-using-WebAPI-in-MAUI-DataGrid-
How to populate data using WebAPI in MAUI DataGrid?
# How to populate data using WebAPI in MAUI DataGrid?
The [.NET MAUI DataGrid](https://www.syncfusion.com/maui-controls/maui-datagrid) supports binding the item source from a Web API.

##### C#
Create a **JSON** data model.

**OrderInfo**
```C#
public class OrderInfo
{
public int OrderID { get; set; }
public string? CustomerID { get; set; }
public int EmployeeID { get; set; }
public double Freight { get; set; }
public string? ShipCity { get; set; }
public bool Verified { get; set; }
public DateTime OrderDate { get; set; }
public string? ShipName { get; set; }
public string? ShipCountry { get; set; }
public DateTime ShippedDate { get; set; }
public string? ShipAddress { get; set; }
}
```
Create a WebApiServices class within the Services folder.

**WebApiServices**

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.

```C#
internal class WebApiServices
{
#region Fields

public static string webApiUrl = "https://ej2services.syncfusion.com/production/web-services/api/Orders"; // Your Web Api here

HttpClient client;

#endregion

#region Constructor

public WebApiServices()
{
client = new HttpClient();
}

#endregion

#region RefreshDataAsync

/// <summary>
/// Retrieves data from the web service.
/// </summary>
/// <returns>Returns the ObservableCollection.</returns>
public async Task<ObservableCollection<OrderInfo>>? ReadDataAsync()
{
var uri = new Uri(webApiUrl);
try
{
//Sends request to retrieve data from the web service for the specified Uri
var response = await client.GetAsync(uri);

if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync(); //Returns the response as JSON string
return JsonConvert.DeserializeObject<ObservableCollection<OrderInfo>>(content)!; //Converts JSON string to ObservableCollection
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(@"ERROR {0}", ex.Message);
}

return null;
}

#endregion
}
```

**OrderInfoViewModel**

Populate the data using the ReadDataAsync() in the viewmodel.

```C#
private async void GenerateData()
{
OrderInfoCollection = await webApiServices.ReadDataAsync()!;
}
```

The following screenshot shows how to to populate data using WebAPI in MAUI DataGrid.

![DataGrid with JSON data](SfDataGrid_WebApi.png)

[View sample in GitHub](https://github.com/SyncfusionExamples/How-to-populate-data-using-WebAPI-in-MAUI-DataGrid)

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.
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).

### Conclusion
I hope you enjoyed learning about how to populate data using WebAPI in MAUI DataGrid.

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.
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.
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!
14 changes: 14 additions & 0 deletions SfDataGridSample/App.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version = "1.0" encoding = "UTF-8" ?>
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SfDataGridSample"
x:Class="SfDataGridSample.App">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles/Colors.xaml" />
<ResourceDictionary Source="Resources/Styles/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
12 changes: 12 additions & 0 deletions SfDataGridSample/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace SfDataGridSample
{
public partial class App : Application
{
public App()
{
InitializeComponent();

MainPage = new AppShell();
}
}
}
15 changes: 15 additions & 0 deletions SfDataGridSample/AppShell.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Shell
x:Class="SfDataGridSample.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SfDataGridSample"
Shell.FlyoutBehavior="Disabled"
Title="SfDataGridSample">

<ShellContent
Title="Home"
ContentTemplate="{DataTemplate local:MainPage}"
Route="MainPage" />

</Shell>
10 changes: 10 additions & 0 deletions SfDataGridSample/AppShell.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace SfDataGridSample
{
public partial class AppShell : Shell
{
public AppShell()
{
InitializeComponent();
}
}
}
53 changes: 53 additions & 0 deletions SfDataGridSample/Helper/WebApiServices.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using Newtonsoft.Json;
using SfDataGridSample.Model;
using System.Collections.ObjectModel;

namespace SfDataGridSample
{
internal class WebApiServices
{
#region Fields

public static string webApiUrl = "https://ej2services.syncfusion.com/production/web-services/api/Orders"; // Your Web Api here

HttpClient client;

#endregion

#region Constructor
public WebApiServices()
{
client = new HttpClient();
}
#endregion

#region RefreshDataAsync

/// <summary>
/// Retrieves data from the web service.
/// </summary>
/// <returns>Returns the ObservableCollection.</returns>
public async Task<ObservableCollection<OrderInfo>>? ReadDataAsync()
{
var uri = new Uri(webApiUrl);
try
{
//Sends request to retrieve data from the web service for the specified Uri
var response = await client.GetAsync(uri);

if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync(); //Returns the response as JSON string
return JsonConvert.DeserializeObject<ObservableCollection<OrderInfo>>(content)!; //Converts JSON string to ObservableCollection
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(@"ERROR {0}", ex.Message);
}

return null;
}
#endregion
}
}
25 changes: 25 additions & 0 deletions SfDataGridSample/MainPage.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:syncfusion="clr-namespace:Syncfusion.Maui.DataGrid;assembly=Syncfusion.Maui.DataGrid"
xmlns:local="clr-namespace:SfDataGridSample"
x:Class="SfDataGridSample.MainPage">

<ContentPage.BindingContext>
<local:OrderInfoViewModel/>
</ContentPage.BindingContext>

<syncfusion:SfDataGrid ItemsSource="{Binding OrderInfoCollection}"
ColumnWidthMode="Auto"
GridLinesVisibility="Both"
HeaderGridLinesVisibility="Both">
<syncfusion:SfDataGrid.Columns>
<syncfusion:DataGridNumericColumn MappingName="OrderID" HeaderText="Order ID" Format="d"/>
<syncfusion:DataGridTextColumn MappingName="CustomerID" HeaderText="Customer ID"/>
<syncfusion:DataGridTextColumn MappingName="ShipName" HeaderText="Ship Name"/>
</syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>



</ContentPage>
18 changes: 18 additions & 0 deletions SfDataGridSample/MainPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Syncfusion.Maui.DataGrid;
using System;
using System.Data;
using System.Data.Common;
using System.Reflection;
namespace SfDataGridSample
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}

}


}
27 changes: 27 additions & 0 deletions SfDataGridSample/MauiProgram.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Microsoft.Extensions.Logging;
using Syncfusion.Maui.Core.Hosting;

namespace SfDataGridSample
{
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureSyncfusionCore()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});

#if DEBUG
builder.Logging.AddDebug();
#endif

return builder.Build();
}
}
}
17 changes: 17 additions & 0 deletions SfDataGridSample/Model/OrderInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace SfDataGridSample.Model
{
public class OrderInfo
{
public int OrderID { get; set; }
public string? CustomerID { get; set; }
public int EmployeeID { get; set; }
public double Freight { get; set; }
public string? ShipCity { get; set; }
public bool Verified { get; set; }
public DateTime OrderDate { get; set; }
public string? ShipName { get; set; }
public string? ShipCountry { get; set; }
public DateTime ShippedDate { get; set; }
public string? ShipAddress { get; set; }
}
}
6 changes: 6 additions & 0 deletions SfDataGridSample/Platforms/Android/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
11 changes: 11 additions & 0 deletions SfDataGridSample/Platforms/Android/MainActivity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Android.App;
using Android.Content.PM;
using Android.OS;

namespace SfDataGridSample
{
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
}
}
16 changes: 16 additions & 0 deletions SfDataGridSample/Platforms/Android/MainApplication.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Android.App;
using Android.Runtime;

namespace SfDataGridSample
{
[Application]
public class MainApplication : MauiApplication
{
public MainApplication(IntPtr handle, JniHandleOwnership ownership)
: base(handle, ownership)
{
}

protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#512BD4</color>
<color name="colorPrimaryDark">#2B0B98</color>
<color name="colorAccent">#2B0B98</color>
</resources>
10 changes: 10 additions & 0 deletions SfDataGridSample/Platforms/MacCatalyst/AppDelegate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Foundation;

namespace SfDataGridSample
{
[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate
{
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
}
14 changes: 14 additions & 0 deletions SfDataGridSample/Platforms/MacCatalyst/Entitlements.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<!-- See https://aka.ms/maui-publish-app-store#add-entitlements for more information about adding entitlements.-->
<dict>
<!-- App Sandbox must be enabled to distribute a MacCatalyst app through the Mac App Store. -->
<key>com.apple.security.app-sandbox</key>
<true/>
<!-- When App Sandbox is enabled, this value is required to open outgoing network connections. -->
<key>com.apple.security.network.client</key>
<true/>
</dict>
</plist>

Loading